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?
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
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