Add / Remove Tabs Dynamically in Bootstrap - Make created tab active

前端 未结 2 1825
清酒与你
清酒与你 2020-12-13 07:15

Here is the snippet to dynamically add / remove bootstrap tabs. Everything works fine, but I would like newly created tab to be active and in focus rather than the tab used

2条回答
  •  萌比男神i
    2020-12-13 07:38

    Here is a solution:

    See JSFiddle

    1. The tab('show') is still being called when the "Add Contact" navlink is clicked. Even though the show tab function is called, no tab content is being displayed because it has no existing contents linked to it. What I did is to add a condition to stop activating that tab.

      $(".nav-tabs").on("click", "a", function (e) {
           e.preventDefault();
           if (!$(this).hasClass('add-contact')) {
               $(this).tab('show');
           }
      })
      
    2. I also removed the data-toggle="tab" attribute to the "Add Contact" navlink. For some reason, it activates the "Add Contact" tab if it's there.

    3. + Add Contact
    4. Upon adding a new tab, trigger the click of the new tab so that the tab('show') function will be called. (see 1)

      $('.add-contact').click(function (e) {
           e.preventDefault();
           var id = $(".nav-tabs").children().length; //think about it ;)
           var tabId = 'contact_' + id;
           $(this).closest('li').before('
    5. New Tab x
    6. '); $('.tab-content').append('
      Contact Form: New Contact ' + id + '
      '); // add this $('.nav-tabs li:nth-child(' + id + ') a').click(); });

提交回复
热议问题