I have my code which enables the user to add and remove tabs in Bootstrap UI Tabs. I've successfully made it, and yes, it works well.
The only problem is it doesn't sort the tab name. For example, there are tabs like this: Tab 1, Tab 2, Tab 3, Tab 4, Tab 5
So when I remove Tab 2, Tab 3 will be Tab 2 then Tab 4 will be Tab 3and so on..
Also, when I remove a tab, an active tab shows Tab 1. (Please see it in jsfiddle)
Any fix with my two problems?
JSFiddle Link: https://jsfiddle.net/cnycmLq0/
<div class="container">
<div class="row">
<div class="col-md-12">
<p>
<button id="btn-add-tab" type="button" class="btn btn-primary pull-right">Add Tab</button>
</p>
<!-- Nav tabs -->
<ul id="tab-list" class="nav nav-tabs" role="tablist">
<li class="active"><a href="#tab1" role="tab" data-toggle="tab">Tab 1</a></li>
</ul>
<!-- Tab panes -->
<div id="tab-content" class="tab-content">
<div class="tab-pane fade in active" id="tab1">Tab 1 content</div>
</div>
</div>
</div>
</div>
JS:
$(document).ready(function() {
var tabID = 1;
$('#btn-add-tab').click(function() {
tabID++;
$('#tab-list').append($('<li><a href="#tab' + tabID + '" role="tab" data-toggle="tab">Tab ' + tabID + '<button class="close" type="button" title="Remove this page">×</button></a></li>'));
$('#tab-content').append($('<div class="tab-pane fade" id="tab' + tabID + '">Tab ' + tabID + ' content</div>'));
});
$('#tab-list').on('click', '.close', function() {
var tabID = $(this).parents('a').attr('href');
$(this).parents('li').remove();
$(tabID).remove();
//display first tab
var tabFirst = $('#tab-list a:first');
tabFirst.tab('show');
});
var list = document.getElementById("tab-list");
});