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?
Tabs can be added dynamically by passing array of items and index value to the addTab method. // New tab title and content inputs are fetched and stored in local variable let title: string = document. getElementById('tab-title').
Approach: To create a tabbed navigation menu, create a basic unordered list with list items as links. Then add classes nav and nav-tabs of bootstrap to unordered list and nav-items class to list items. Example 1: HTML.
You can do this by adding styles to tab-pane. Let's add a style class to div with style class “tab-content” call “my-tab.” This new style class will override the default class properties. Now you can add the following line of code to CSS.
You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Use these data attributes on .
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');
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);
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');
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