Jacob Ruvalcaba
Jacob Ruvalcaba

Reputation: 47

How to tell which tab is active

I am using bootstrap 3 and I currently have 3 tabs on a page like so

<ul class="nav nav-tabs" role="tablist">
      <li role="presentation" class="active"><a href="#one" aria-controls="one" role="tab" data-toggle="tab">One </a></li>
      <li role="presentation"><a href="#two" aria-controls="two" role="tab" data-toggle="tab">Two </a></li>
      <li role="presentation"><a href="#three" aria-controls="three" role="tab" data-toggle="tab"> Three</a></li>
 </ul>

Currently I can call this to get me to activate/show a specific tab like

 $('.nav-tabs a[href="#one"]').tab('show');

But let say I am on another tab and I update something on that tab, and then I want to show that active tab. How would I do this?

UPDATE I added this

var activetab = $('.allschedules').find('li.active');

which returns me an object with properties of the current tab. How do I get teh name of the a href?

Upvotes: 2

Views: 2948

Answers (1)

CDelaney
CDelaney

Reputation: 1248

You can do a 2nd query to find the child <a> element, and then check its hash property to get the name from the href.

var activeTabName = $('li.active').find('a')[0].hash;
$('#active-tab-name').text(activeTabName);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<ul class="nav nav-tabs" role="tablist">
      <li role="presentation" class="active"><a href="#one" aria-controls="one" role="tab" data-toggle="tab">One </a></li>
      <li role="presentation"><a href="#two" aria-controls="two" role="tab" data-toggle="tab">Two </a></li>
      <li role="presentation"><a href="#three" aria-controls="three" role="tab" data-toggle="tab"> Three</a></li>
</ul>

<span id="active-tab-name"></span>

Upvotes: 2

Related Questions