Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 4 tabs: get index number of clicked tab?

I am trying to figure out which tab the user clicked on by its index, e.g. they clicked on the second of five tabs.

I can get the total number of tabs by adding an ID to the nav:

this.numTabs = $('#myTabset').children().length;

from the Bootstrap 4 docs, I can get the clicked tab:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
      console.log(e.target); // newly activated tab
    });

Which logs:

<a class="nav-link" data-toggle="tab" href="#profileS" role="tab" aria-selected="false">Profile</a>

So I can get all aspects of the clicked tab, but how to get which "number" tab it is?

like image 422
Steve Avatar asked Nov 19 '25 08:11

Steve


1 Answers

Use the jQuery .index() method like this...

$('a[data-toggle="tab"]').on('shown.bs.tab', function(e) {
    var idx = $(this).index('a[data-toggle="tab"]');
});

Demo: https://www.codeply.com/go/GeNHX340fc

like image 91
Zim Avatar answered Nov 21 '25 20:11

Zim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!