Add tabs dynamically when a button is clicked
HTML code:
<div id="container-1"> <ul> <li><a href="#fragment-1">List</a></li> <li><a href="#fragment-2">List</a></li> <li><a href="#fragment-3">List</a></li> </ul> <div id="fragment-1">one</div> <div id="fragment-2">two</div> <div id="fragment-3">three</div> </div> <button id="add_tab">Add Tab</button> and I want to add another snippet-4 tab, which is on the onclick event. this div tab is outside of <div id="container-1"> . and I use the following java script:
$(document).ready(function() { var tabs = $("#container-1").tabs(); var tabCounter = 1; $('#add_tab').click( function(){ var ul = tabs.find( "ul" ); $( "<li><a href='#fragment-4'>Call Detials</a></li>" ).appendTo( ul ); tabs.tabs( "refresh" ); tabs.tabs('select', 1); }); }); With this function, I can get a dynamic tab, but not the content that is recorded on this tab. so please suggest me what can i do?
+4
4 answers
$(document).ready(function() { var tabs = $("#container-1").tabs(); var tabCounter = 1; $('#add_tab').click( function(){ var ul = tabs.find( "ul" ); var current_idx = ul.find("li").length + 1; // Get correct index for id $("<li><a href='#fragment-" + current_idx + "'>Call Details</a></li>" ).appendTo( ul ); tabs.append( $('#callDetail') ); tabs.tabs("refresh"); tabs.tabs("select", 1); }); }); 0
In addition to adding li you need to add a div with content. The div identifier must match the href attribute of the li element.
Something like that:
EDIT : dynamic tab identifiers added
$(document).ready(function () { var tabs = $("#container-1").tabs(); var tabCounter = 3; $('#add_tab').click(function () { tabCounter++; var ul = tabs.find("ul"); $('<li><a href="#fragment-' + tabCounter + '">Call Detials</a></li>').appendTo(ul); tabs.append('<div id="fragment-' + tabCounter + '">Hello there ' + tabCounter + '</div>'); tabs.tabs("refresh"); tabs.tabs('select', 1); }); }); +1
Along with adding li you also need to add the contents of the div.
$(document).ready(function() { var tabs = $("#container-1").tabs(); var tabCounter = tabs.find('ul').first().children().length; $('#add_tab').click( function(){ var ul = tabs.find( "ul" ); $( '<li><a href="#fragment-' + ++tabCounter + '">Call Detials</a></li>' ).appendTo( ul ); $( '<div id="fragment-' + tabCounter + '">'+ tabCounter +'</div>' ).appendTo( tabs ); tabs.tabs( "refresh" ); tabs.tabs('select', tabCounter - 1); }); }); Demo: Fiddle
0
$(document).ready(function() { var tabs = $("#container-1").tabs(); $('#add_tab').click( function(){ var tabCounter = $('#container-1 ul li').length; // return number of tabs // add tabs with button $('#container-1').append("<div id='fragment-"+tabCounter+">Content</div>"); $('#container-1 ul').append("<li><a href='#fragment-"+tabCounter+">"+tabCounter+"</a></li>"); // Note : if you want show literal number, use something like .replace() tabs.tabs("refresh"); tabs.tabs('select', tabCounter); }); }); 0