jQuery UI tabs. How to select a tab based on its id not based on index
Note: Due to changes made to jQuery 1.9 and jQuery UI, this answer is no longer the correct one. Please see @stankovski's answer below.
You need to find the tab's index first (which is just its position in a list) and then specifically select the tab using jQuery UI's provided select event (tabs->select).
var index = $('#tabs ul').index($('#tabId'));
$('#tabs ul').tabs('select', index);
Update: BTW - I do realize that this is (ultimately) still selecting by index. But, it doesn't require that you know the specific position of the tabs (particularly when they are dynamically generated as asked in the question).
It may have side effects if there are other listeners, and it doesn't feel as nice as interacting through the plugins API -- but it gives a less verbose code if you just "click" the tab, rather than count it's index and set it active afterwards, and it's pretty intuitive what's going on. Also it wont fail if the ui-guys decide to rename the option again.
$('#tabs').tabs();
$('#tabs a[href="#tabtwo"]').click();
It's intriguing, though, that the ui tabs code has a meta-function (_getIndex
) with the comment:
"meta-function to give users option to provide a href string instead of a numerical index"
but does not use it when setting the active option, only when calling enable, disable and load.
Accepted answer didn't work for me either, however I found solution in a similar thread: Switch to selected tab by name in Jquery-UI Tabs
var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$('#tabs').tabs('select', index);
With jQuery UI >= 1.9:
var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);
From the most recent document, the select method takes an index or the id of the tab's panel (the href hash value). The documentation states:
Select a tab, as if it were clicked. The second argument is the zero-based index of the tab to be selected or the id selector of the panel the tab is associated with (the tab's href fragment identifier, e.g. hash, points to the panel's id).
So, given a layout like
<div id="myTabs">
<ul class="tabs">
<li><a href="#tabone">tabone</a></li>
<li><a href="#tabtwo">tabtwo</a></li>
</ul>
</div>
the following works
$('#myTabs').tabs('select', '#tabtwo');
Here is an example.
UPDATE
The above solution works in jQuery UI versions less than 1.9. For a solution in versions 1.9+ see @stankovski's answer.