Adding Dynamic Tab in BootStrap Tabs
Asked Answered
H

3

11

I am using Twiter Bootstrap Tabs on my page. I want to dynamically add tabs in the view. Currently I am using this code, which is not working

$('#tab').append('<li><a href="#tabname" data-toggle="tab">Tab Name</a></li>');
$('#myTabContent').append('<div class="tab-pane fade in active" id="tabname"><p>tab content</p></div>');
$('#tab a:last').tab('show');

Can Any body tell me what I am missing?

Hillhouse answered 2/4, 2012 at 16:16 Comment(1)
having same issue. when I append <li> to the tab list, it adds the element but strips out the id field and innerHTML. If i find a solution i shall returnSheath
H
14

Now I am using this code that's working

$('div.active').removeClass('active').removeClass('in');
$('li.active').removeClass('active');

$('#myTabContent').append('<div class="tab-pane in active" id="new_tab_id"><p> Loading content ...</p></div>');
$('#tab').append('<li><a href="#new_tab_id" data-toggle="tab">Tab Name</a></li>');
$('#tab a:last').tab('show');
Hillhouse answered 13/4, 2012 at 20:34 Comment(0)
A
6

In my project, I use this code to add tabs

app = function(){
return {
  tabAdd: function(sel, id, label, content, show){
    var tabs = $(sel);
    $('div.active', tabs).removeClass('in').add($('li.active', tabs)).removeClass('active');
    $('.tab-content', tabs).append('<div class="tab-pane in active" id="'+id+'">'+content+'</div>');
    $('.nav-tabs', tabs).append('<li><a href="#'+id+'" data-toggle="tab">'+label+'</a></li>');
    if(show==true) $('.nav-tabs a:last').tab('show');
  }
}}();
//Example
app.tabAdd('#tabs', 'idNew', 'Label', 'Сontent', true);
Abduction answered 26/9, 2012 at 10:30 Comment(1)
Maybe you can explain what you did and why this is going to work.Fennel
S
2

In case it helps anyone, variant I used that seemed to make more sense.

this.addTab = function(id, label, content ){

    var nav     = $( tab_nav_id );  // ID of your nav-tabs element
    var tabs    = $( tab_list_id ); // ID of your tab-content element

    var new_tab = $('<div>').addClass( 'tab-pane in').attr('id', id).append( content );
    var new_li  = $('<li>').append( $('<a>').attr('href', "#" + id).attr('data-toggle', 'tab').append( label ) );

    tabs.append( new_tab );
    nav.append( new_li );

    return new_li;
};

Returning the new_li makes it convenient from the calling class.

var tab = this.addTab( 'some_key', 'Tab Title', 'Tab Content' );
// do stuff with tab
tab.find('a').tab('show');
Smarten answered 30/12, 2013 at 18:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.