Selected tab id?
Asked Answered
K

5

8

I have the following script which gets the index of the selected tab:

http://jsfiddle.net/oshirowanen/eWncA/

Is it possible to get the id instead, if the li's had id's. If it is easier to get it from elsewhere, then that would also be fine, i.e. the related div tags, or somewhere else.

Kirit answered 14/3, 2011 at 14:39 Comment(1)
I don't agree, posting links to jsfiddle allows users to quickly and easily make changes to the script, without having to re-create it on their own computer which would take longer for the person trying to help.Kirit
K
9

jQuery UI just adds a class to the selected li. You could just pull the li with the selected class out like this:

   var id = $("li.tab.ui-tabs-selected").attr("id");

If you wanted to get one of the unselected tabs you could do something like this:

var id = $("li.tab:not(.ui-tabs-selected)").first().attr("id");

Working example:

http://jsfiddle.net/UBs9m/2/

Kelcey answered 14/3, 2011 at 14:46 Comment(3)
Your demo doesn't seem to work. It seems to be returning the index.Kirit
I prefer Eugene's solution below because, although it is technically less efficient, it is not dependent on jQuery's default behavior and it shows the user how s/he can get the id of a non-selected tab for a different, future situation.Tootsie
updated my jsfiddle link, also included a way to get a 'non-selected' tab in case that's a concernKelcey
P
4
var id = $("li.tab:eq("+selected+")").attr('id');
Photosynthesis answered 14/3, 2011 at 14:42 Comment(0)
S
3

If you're able to simply use the Tabs control's select event handler, this works fine:

$('#tabs').tabs({
    select: function( evt, ui ) {
        console.log( $(ui.panel).attr( 'id' ) );
    }
});

Also, here's a handy reference for the different ui object properties.

Sileas answered 21/12, 2011 at 23:22 Comment(0)
C
2

If you are using jquery tabs (new version):

<div id="tabs">
        <ul>
            <li data-value="tab1"><a href="#tab1">Name of tab1</a></li>
            <li data-value="tab2"><a href="#tab2">Name of tab2</a></li>
        </ul>
        <div id="tab1">
        </div>
        <div id="tab2">
        </div>
 </div>       

 //get id in init
 $(function () {
    $("#tabs").tabs({
        activate: function(event ,ui) {
           var id = $(ui.newPanel).prop('id');
        }
      }
    );
 });
 var id = $("#tabs li.ui-state-active").attr('data-value'); //get id in other function
Catapult answered 26/6, 2013 at 9:25 Comment(0)
P
0

If you're coming here via Google like myself, and are using jQuery UI 1.9.X, use the activate or beforeActivate events to get the id:

$('selector').tabs({
  activate: function(e, ui) {
    var id = $(ui.newPanel).prop('id');
  }
});

Documentation

Pasta answered 14/6, 2013 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.