title: jQuery Bootstrap Dynamic Tabs (Add & Remove)
body: <p>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.</p>
  
  <p>The only problem is it doesn't sort the tab name. For example, there are tabs like this: <code>Tab 1</code>, <code>Tab 2</code>, <code>Tab 3</code>, <code>Tab 4</code>, <code>Tab 5</code></p>
  
  <p>So when I remove <code>Tab 2</code>, <code>Tab 3</code> will be <code>Tab 2</code> then <code>Tab 4</code> will be <code>Tab 3</code>and so on..</p>
  
  <p>Also, when I remove a tab, an active tab shows Tab 1. (Please see it in jsfiddle) </p>
  
  <p>Any fix with my two problems? </p>
  
  <p>JSFiddle Link: <a href="https://jsfiddle.net/cnycmLq0/" rel="nofollow">https://jsfiddle.net/cnycmLq0/</a></p>
  
  <pre><code>&lt;div class="container"&gt;
      &lt;div class="row"&gt;
          &lt;div class="col-md-12"&gt;
              &lt;p&gt;
                  &lt;button id="btn-add-tab" type="button" class="btn btn-primary pull-right"&gt;Add Tab&lt;/button&gt;
              &lt;/p&gt;
              &lt;!-- Nav tabs --&gt;
              &lt;ul id="tab-list" class="nav nav-tabs" role="tablist"&gt;
                  &lt;li class="active"&gt;&lt;a href="#tab1" role="tab" data-toggle="tab"&gt;Tab 1&lt;/a&gt;&lt;/li&gt;
              &lt;/ul&gt;
  
              &lt;!-- Tab panes --&gt;
              &lt;div id="tab-content" class="tab-content"&gt;
                  &lt;div class="tab-pane fade in active" id="tab1"&gt;Tab 1 content&lt;/div&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>JS:</p>
  
  <pre><code>    $(document).ready(function() {
          var tabID = 1;
          $('#btn-add-tab').click(function() {
              tabID++;
              $('#tab-list').append($('&lt;li&gt;&lt;a href="#tab' + tabID + '" role="tab" data-toggle="tab"&gt;Tab ' + tabID + '&lt;button class="close" type="button" title="Remove this page"&gt;×&lt;/button&gt;&lt;/a&gt;&lt;/li&gt;'));
              $('#tab-content').append($('&lt;div class="tab-pane fade" id="tab' + tabID + '"&gt;Tab ' + tabID + ' content&lt;/div&gt;'));
          });
          $('#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");
      });
  </code></pre>