48

I have two tabs and configured usign jQuery UI.

ul  class="tabs"
  li  tabone
  li tabtwo
ul

dynamically from C# code behind I will hide or select some tab let say tabtwo and the other tab has to be hidden or not shown. I can do this in JavaScript using .tabs({selected:1}); and .tabs(disable:0). but I don't want to use the tab indexes to do so.

Is there any alternate to select tabs based on their name/id?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
user695663
  • 11,856
  • 8
  • 26
  • 32
  • Post some code for us to work with yeah? – Chris Dowdeswell May 06 '11 at 14:23
  • this is the answer http://stackoverflow.com/questions/5914110/how-to-get-the-index-of-an-li-in-a-ul – user695663 May 06 '11 at 16:48
  • possible duplicate of [Switch to selected tab by name in Jquery-UI Tabs](http://stackoverflow.com/questions/578348/switch-to-selected-tab-by-name-in-jquery-ui-tabs) – Eran Medan Feb 01 '13 at 14:46
  • Please mark @Garett's answer as the accepted one, it's the most correct as it is now possible to do simply this: `$("#tabs").tabs("select", "#sample-tab-1");` From the docs: "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)." See: http://jqueryui.com/tabs/#method-select – Eran Medan Feb 01 '13 at 14:57

14 Answers14

138

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);
Community
  • 1
  • 1
stankovski
  • 2,129
  • 2
  • 16
  • 11
  • 1
    There is a much easier solution now, it seems that using the id works as well as the index, e.g. simply doing this will work out of the box... `$("#tabs").tabs("select", "#sample-tab-1");` This is well documented in the official docs: "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)." – Eran Medan Feb 01 '13 at 14:49
  • 1
    This update for `jQuery UI >= 1.9` saved my life. I had old code that just stopped working after updating. Thanks @Andreas Schwarz. That's why it's so important to update old answers. I always try to do that... :) – Leniel Maccaferri Feb 11 '13 at 04:20
  • 1
    I put other solution here: http://jsfiddle.net/WXxnr/ I think that it's easier and works for Jquery 2.0 – Curlas Feb 05 '14 at 12:01
  • This doesn't handle all use cases, for example tabs can be loading ajax content from a url or from a script, so the anchor element's href won't always correspond with panel id. To handle all use cases, use the parent li element's 'aria-controls' attribute. See my answer below. – JohnRDOrazio Oct 17 '15 at 10:00
  • In mycase i had to use it without the "parent()" to get the correct index. was adding tabs dynamcally – Shaakir Aug 29 '16 at 18:52
19

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).

JasCav
  • 34,458
  • 20
  • 113
  • 170
  • 1
    this is not working. it always returns -1 for the index. do you know why? – user695663 May 06 '11 at 15:54
  • @user695663 - Are you putting the right ID value in? (It won't be #tabId - it'll be whatever the ID of your tab is.) – JasCav May 06 '11 at 16:12
  • This appears to be jumping to the top of the page after switching tabs. Can I switch tabs without jumping to the top? – Michael Capobianco Jun 19 '12 at 13:43
  • 7
    This answer is no longer relevant due to jQuery UI making drastic changes to its API. – Donald T Jan 18 '13 at 19:43
  • Please stop downvoting. This *was* the correct answer at the time this question was asked. Please just upvote @stankovski's correct answer. (There is a reason I updated this to note that.) – JasCav Apr 25 '13 at 13:57
  • 1
    @JasCav - Would you like for the answer to remain for posterity? I can delete it if you'd think that would be best. – Brad Larson Apr 25 '13 at 17:33
  • @BradLarson - Well, this goes to a bigger issue - are we going to hit up old answers and ding them after the fact even if they were correct at the time? Are we going to try to maintain for new questions (or should new questions be asked)? I would posit that the answer is for the question at the time. And, deleting my question, of course, would take away the 35 points I still have on the question when a true-up is done. That seems poor to ding people for answering correctly at the time the question was asked. Thoughts? – JasCav Apr 25 '13 at 19:22
  • @JasCav - This sounds like a good question for Meta. In the past, others have requested the deletion of their obsolete answers, even knowing that the previous votes would go with it. Some have wanted to keep them around, even though they accrue downvotes for no longer being viable. I don't know what the consensus is here. – Brad Larson Apr 25 '13 at 19:28
  • @BradLarson - Okay. Leave this for now then, but I'll ask in Meta. I appreciate your help. (A "locked but pointing to the new answer" option would be excellent. I would gladly point to stankovski's new answer and say mine has gone obsolete, but keep mine for posterity. It could push his to the top or something above my answer.) – JasCav Apr 25 '13 at 19:32
  • I put other solution here: http://jsfiddle.net/WXxnr/ I think that it's easier and works for Jquery 2.0 – Curlas Feb 05 '14 at 12:01
15

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.

Community
  • 1
  • 1
Garett
  • 16,632
  • 5
  • 55
  • 63
2

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.

Torin Finnemann
  • 771
  • 9
  • 11
2

As per UI Doc :

  1. First get index of tab which you want to activate.

    var index = $('#tabs a[href="'+id+'"]').parent().index();
    
  2. Activate it

    tabs.tabs( "option", "active", index );
    
Mohan Dere
  • 4,497
  • 1
  • 25
  • 21
2

Active 1st tab

$("#workflowTab").tabs({ active: 0 });

Active last tab

$("#workflowTab").tabs({ active: -1 });

Active 2nd tab

$("#workflowTab").tabs({ active: 1 });

Its work like an array

Carl0s1z
  • 4,683
  • 7
  • 32
  • 47
2

This is the answer

var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);
Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
1

None of these answers worked for me. I just by-passed the problem. I did this:

$('#tabs-tab1').removeClass('tabs-hide');
$('#tabs-tab2').addClass('tabs-hide');
$('#container-tabs a[href="#tabs-tab2"]').parent().removeClass('tabs-selected');
$('#container-tabs a[href="#tabs-tab1"]').parent().addClass('tabs-selected');

It works great.

Eli
  • 414
  • 5
  • 10
1
                <div id="tabs" style="width: 290px">
                    <ul >
                        <li><a id="myTab1" href="#tabs-1" style="color: Green">Báo cáo chuẩn</a></li>
                        <li><a id="myTab2" href="#tabs-2" style="color: Green">Báo cáo mở rộng</a></li>
                    </ul>
                    <div id="tabs-1" style="overflow-x: auto">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/ReportDate")"><span class=""></span>Báo cáo theo ngày</a></li>

                        </ul>
                    </div>
                    <div id="tabs-2" style="overflow-x: auto; height: 290px">
                        <ul class="nav">

                            <li><a href="@Url.Content("~/Report/PetrolReport#tabs-2")"><span class=""></span>Báo cáo nhiên liệu</a></li>
                        </ul>
                    </div>
                </div>


        var index = $("#tabs div").index($("#tabs-1" ));
        $("#tabs").tabs("select", index);
       $("#tabs-1")[0].classList.remove("ui-tabs-hide");
1

Building on @stankovski's answer, a more precise way of doing it which will work for all use cases (for example, when a tab is loading via ajax and so the anchor's href attribute doesn't correspond with the hash), the id in any case will correspond with the li element's "aria-controls" attribute. So for example if you are trying to activate a tab based on the location.hash, which is set to the tab id, then it is better to look for "aria-controls" than for "href".

With jQuery UI >= 1.9:

var index = $('#tabs > ul > li[aria-controls="simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);

In the case of setting and checking the url hash:

When creating the tabs, use the 'activate' event to set the location.hash to the panel id:

$('#tabs').tabs({
  activate: function(event, ui) {                   
      var scrollTop = $(window).scrollTop(); // save current scroll position
      window.location.hash = ui.newPanel.attr('id');
      $(window).scrollTop(scrollTop); // keep scroll at current position
  }    
});

Then use the window hashchange event to compare the location.hash to the panel id (do this by looking for the li element's aria-controls attribute):

$(window).on('hashchange', function () {
  if (!location.hash) {
    $('#tabs').tabs('option', 'active', 0);
    return;
  }

  $('#tabs > ul > li').each(function (index, li) {
    if ('#' + $(li).attr('aria-controls') == location.hash) {
      $('#tabs').tabs('option', 'active', index);
      return;
    }
  });


});

This will handle all cases, even where tabs use ajax. Also if you have nested tabs, it isn't too difficult to handle that either using a little more logic.

JohnRDOrazio
  • 1,358
  • 2
  • 15
  • 28
1

I found this works more easily than getting an index. For my needs, I am selecting a tab based off a url hash

var target = window.location.hash.replace(/#/,'#tab-');
if (target) { 
    jQuery('a[href='+target+']').click().parent().trigger('keydown');      
}   
0

I did it like this

if (document.location.hash != '') {
   //get the index from URL hash
   var tabSelect = document.location.hash.substr(1, document.location.hash.length);
   console.log("tabSelect: " + tabSelect);
   if (tabSelect == 'discount')
   { 
       var index = $('#myTab a[href="#discount"]').parent().index();
       $("#tabs").tabs("option", "active", index);
       $($('#myTab a[href="#discount"]')).tab('show');
   }
}
NoWar
  • 36,338
  • 80
  • 323
  • 498
0
$("#tabs").tabs({active: [0,2], disabled: [3], selected: 2});

Where Selected is used for open Particular Tab or Select Particular Tab on onload.

Shwabster
  • 479
  • 1
  • 10
  • 27
Durgesh.M
  • 9
  • 2
0

I make a wild assumption that you really have layout as:

<ul  class="tabs">
  <li id="tabone">one</li>
  <li id="tabtwo">two</li>
</ul>

IF that assumption is correct, you simply use the ID to select the "tab"

$('#tabone').css("display","none");

EDIT: select the tab on your layout:

var index = $('.tabs ul').index($('#tabone')); 
$('.tabs ul').tabs('select', index); 
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100