I was doing a project on HTML and jQuery recently. Thing I want to achieve now is to create dynamic tab with particular data on a button click.
My code for JQuery-UI tab is
$(document).ready(function() {
var $tabs = $("#container-1").tabs();
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabCounter = 2;
$('#add_tab').click( function(){
var label = 'New',
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = 'hi';
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
tabs.tabs( "refresh" );
tabCounter++;
});
$('#new').click( function(){
$tabs.tabs('select', 2);
});
});
My HTML file
<div id="container-1">
<ul>
<li><a href="#fragment-1">List</a></li>
</ul>
<div id="fragment-1">
</div>
</div>
<button id="add_tab">Add Tab</button>
When i click 'add' button in the console of firebug I'm get error:
ReferenceError: tabs is not defined
http://localhost:3000/
Line 38
I'm not so good with jquery-ui. How do I fix this problem?
The problem is with your script.So try this
$(document).ready(function() {
var tabs = $("#container-1").tabs();
var tabCounter = 1;
$('#add_tab').click( function(){
var ul = tabs.find( "ul" );
$( "<li><a href='#newtab'>New Tab</a></li>" ).appendTo( ul );
$( "<div id='newtab'>Name :<input type='text'></input></div>" ).appendTo( tabs );
tabs.tabs( "refresh" );
tabs.tabs('select', 1);
});
});
the only problem in your code was that you defined in the beginning $tabs
and later called for tabs
without the dollar sine. I just removed the dollar sine and it works the way you expected (note the var tabs definition on second line) ... I aswel added code to the jsfiddle.
$(document).ready(function() {
var tabs = $("#container-1").tabs();
var tabTemplate = "<li><a href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>",
tabCounter = 2;
$('#add_tab').click( function(){
var label = 'New',
id = "tabs-" + tabCounter,
li = $( tabTemplate.replace( /#\{href\}/g, "#" + id ).replace( /#\{label\}/g, label ) ),
tabContentHtml = 'hi';
tabs.find( ".ui-tabs-nav" ).append( li );
tabs.append( "<div id='" + id + "'><p>" + tabContentHtml + "</p></div>" );
tabs.tabs( "refresh" );
tabCounter++;
});
$('#new').click( function(){
$tabs.tabs('select', 2);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With