[javascript] jQuery UI Tabs - How to Get Currently Selected Tab Index

I know this specific question has been asked before, but I am not getting any results using the bind() event on the jQuery UI Tabs plugin.

I just need the index of the newly selected tab to perform an action when the tab is clicked. bind() allows me to hook into the select event, but my usual method of getting the currently selected tab does not work. It returns the previously selected tab index, not the new one:

var selectedTab = $("#TabList").tabs().data("selected.tabs");

Here is the code I am attempting to use to get the currently selected tab:

$("#TabList").bind("tabsselect", function(event, ui) {

});

When I use this code, the ui object comes back undefined. From the documentation, this should be the object I'm using to hook into the newly selected index using ui.tab. I have tried this on the initial tabs() call and also on its own. Am I doing something wrong here?

This question is related to javascript jquery jquery-ui tabs jquery-ui-tabs

The answer is


Another way to get the selected tab index is:

var index = jQuery('#tabs').data('tabs').options.selected;

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.


If you want to ensure ui.newTab.index() is available in all situations (local and remote tabs), then call it in the activate function as the documentation says:

$("#tabs").tabs({
        activate: function(event, ui){
             alert(ui.newTab.index());
             // You can also use this to set another tab, see fiddle...
             // $("#other-tabs").tabs("option", "active", ui.newTab.index());                   
        },
});

http://jsfiddle.net/7v7n0v3j/


the easiest way of doing this is

$("#tabs div[aria-hidden='false']");

and for index

$("#tabs div[aria-hidden='false']").index();

var $tabs = $('#tabs-menu').tabs();
// jquery ui 1.8
var selected = $tabs.tabs('option', 'selected');
// jquery ui 1.9+
var active = $tabs.tabs('option', 'active');

If you want to ensure ui.newTab.index() is available in all situations (local and remote tabs), then call it in the activate function as the documentation says:

$("#tabs").tabs({
        activate: function(event, ui){
             alert(ui.newTab.index());
             // You can also use this to set another tab, see fiddle...
             // $("#other-tabs").tabs("option", "active", ui.newTab.index());                   
        },
});

http://jsfiddle.net/7v7n0v3j/


If you need to get the tab index from outside the context of a tabs event, use this:

function getSelectedTabIndex() { 
    return $("#TabList").tabs('option', 'selected');
}

Update: From version 1.9 'selected' is changed to 'active'

$("#TabList").tabs('option', 'active')

$("#tabs").tabs({
    activate: function(event, ui) {
        new_index = ui.newTab.index()+1;
        //do anything
    }
});

this changed with version 1.9

something like

 $(document).ready(function () {
            $('#tabs').tabs({
                activate: function (event, ui) {
                    var act = $("#tabs").tabs("option", "active");
                    $("#<%= hidLastTab.ClientID %>").val(act);
                    //console.log($(ui.newTab));
                    //console.log($(ui.oldTab));
                }
            });

            if ($("#<%= hidLastTab.ClientID %>").val() != "") 
            {
                $("#tabs").tabs("option", "active", $("#<%= hidLastTab.ClientID %>").val());
            }


        });

should be used. This is working fine for me ;-)


You can post below answer in your next post

var selectedTabIndex= $("#tabs").tabs('option', 'active');

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.


this changed with version 1.9

something like

 $(document).ready(function () {
            $('#tabs').tabs({
                activate: function (event, ui) {
                    var act = $("#tabs").tabs("option", "active");
                    $("#<%= hidLastTab.ClientID %>").val(act);
                    //console.log($(ui.newTab));
                    //console.log($(ui.oldTab));
                }
            });

            if ($("#<%= hidLastTab.ClientID %>").val() != "") 
            {
                $("#tabs").tabs("option", "active", $("#<%= hidLastTab.ClientID %>").val());
            }


        });

should be used. This is working fine for me ;-)


$( "#tabs" ).tabs( "option", "active" )

then you will have the index of tab from 0

simple


When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.


take a hidden variable like '<input type="hidden" id="sel_tab" name="sel_tab" value="" />' and on each tab's onclick event write code like ...

<li><a href="#tabs-0" onclick="document.getElementById('sel_tab').value=0;" >TAB -1</a></li>
<li><a href="#tabs-1" onclick="document.getElementById('sel_tab').value=1;" >TAB -2</a></li>

you can get the value of 'sel_tab' on posted page. :) , simple !!!


In case if you find Active tab Index and then point to Active Tab

First get the Active index

var activeIndex = $("#panel").tabs('option', 'active');

Then using the css class get the tab content panel

// this will return the html element
var element=   $("#panel").find( ".ui-tabs-panel" )[activeIndex]; 

now wrapped it in jQuery object to further use it

 var tabContent$ = $(element);

here i want to add two info the class .ui-tabs-nav is for Navigation associated with and .ui-tabs-panel is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation


var $tabs = $('#tabs-menu').tabs();
// jquery ui 1.8
var selected = $tabs.tabs('option', 'selected');
// jquery ui 1.9+
var active = $tabs.tabs('option', 'active');

UPDATE [Sun 08/26/2012] This answer has become so popular that I decided to make it into a full-fledged blog/tutorial
Please visit My Blog Here to see the latest in easy access information to working with tabs in jQueryUI
Also included (in the blog too) is a jsFiddle


¡¡¡ Update! Please note: In newer versions of jQueryUI (1.9+), ui-tabs-selected has been replaced with ui-tabs-active. !!!


I know this thread is old, but something I didn't see mentioned was how to get the "selected tab" (Currently dropped down panel) from somewhere other than the "tab events". I do have a simply way ...

var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)');

And to easily get the index, of course there is the way listed on the site ...

var $tabs = $('#example').tabs();
var selected = $tabs.tabs('option', 'selected'); // => 0

However, you could use my first method to get the index and anything you want about that panel pretty easy ...

var curTab = $('.ui-tabs-panel:not(.ui-tabs-hide)'),
    curTabIndex = curTab.index(),
    curTabID = curTab.prop("id"),
    curTabCls = curTab.attr("class");
        //  etc ....

PS. If you use an iframe variable then .find('.ui-tabs-panel:not(.ui-tabs-hide)'), you will find it easy to do this for selected tabs in frames as well. Remember, jQuery already did all the hard work, no need to reinvent the wheel!

Just to expand (updated)

Question was brought up to me, "What if there are more than one tabs areas on the view?" Again, just think simple, use my same setup but use an ID to identify which tabs you want to get hold of.

For example, if you have:

$('#example-1').tabs();
$('#example-2').tabs();

And you want the current panel of the second tab set:

var curTabPanel = $('#example-2 .ui-tabs-panel:not(.ui-tabs-hide)');

And if you want the ACTUAL tab and not the panel (really easy, which is why I ddn't mention it before but I suppose I will now, just to be thorough)

// for page with only one set of tabs
var curTab = $('.ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+

// for page with multiple sets of tabs
var curTab2 = $('#example-2 .ui-tabs-selected'); // '.ui-tabs-active' in jQuery 1.9+

Again, remember, jQuery did all the hard work, don't think so hard.


You can find it via:

$(yourEl).tabs({
    activate: function(event, ui) {
        console.log(ui.newPanel.index());
    }
});

I found the code below does the trick. Sets a variable of the newly selected tab index

$("#tabs").tabs({
    activate: function (e, ui) {
        currentTabIndex =ui.newTab.index().toString();
    }
});

In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.


If you're using JQuery UI version 1.9.0 or above, you can access ui.newTab.index() inside your function and get what you need.

For earlier versions use ui.index.


Another way to get the selected tab index is:

var index = jQuery('#tabs').data('tabs').options.selected;

take a hidden variable like '<input type="hidden" id="sel_tab" name="sel_tab" value="" />' and on each tab's onclick event write code like ...

<li><a href="#tabs-0" onclick="document.getElementById('sel_tab').value=0;" >TAB -1</a></li>
<li><a href="#tabs-1" onclick="document.getElementById('sel_tab').value=1;" >TAB -2</a></li>

you can get the value of 'sel_tab' on posted page. :) , simple !!!


Try the following:

var $tabs = $('#tabs-menu').tabs();

var selected = $tabs.tabs('option', 'selected');

var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;

$("#tabs").tabs({  
    load:  function(event, ui){  
        var anchor = ui.tab.find(".ui-tabs-anchor");  
        var url = anchor.attr('href');  
    }  
});  

In the url variable you will get the current tab's HREF / URL


$( "#tabs" ).tabs( "option", "active" )

then you will have the index of tab from 0

simple


You can post below answer in your next post

var selectedTabIndex= $("#tabs").tabs('option', 'active');

In case if you find Active tab Index and then point to Active Tab

First get the Active index

var activeIndex = $("#panel").tabs('option', 'active');

Then using the css class get the tab content panel

// this will return the html element
var element=   $("#panel").find( ".ui-tabs-panel" )[activeIndex]; 

now wrapped it in jQuery object to further use it

 var tabContent$ = $(element);

here i want to add two info the class .ui-tabs-nav is for Navigation associated with and .ui-tabs-panel is associated with tab content panel. in this link demo in jquery ui website you will see this class is used - http://jqueryui.com/tabs/#manipulation


If you're using JQuery UI version 1.9.0 or above, you can access ui.newTab.index() inside your function and get what you need.

For earlier versions use ui.index.


You can find it via:

$(yourEl).tabs({
    activate: function(event, ui) {
        console.log(ui.newPanel.index());
    }
});

the easiest way of doing this is

$("#tabs div[aria-hidden='false']");

and for index

$("#tabs div[aria-hidden='false']").index();

If you need to get the tab index from outside the context of a tabs event, use this:

function getSelectedTabIndex() { 
    return $("#TabList").tabs('option', 'selected');
}

Update: From version 1.9 'selected' is changed to 'active'

$("#TabList").tabs('option', 'active')

$("#tabs").tabs({  
    load:  function(event, ui){  
        var anchor = ui.tab.find(".ui-tabs-anchor");  
        var url = anchor.attr('href');  
    }  
});  

In the url variable you will get the current tab's HREF / URL


Try the following:

var $tabs = $('#tabs-menu').tabs();

var selected = $tabs.tabs('option', 'selected');

var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;

$("#tabs").tabs({
    activate: function(event, ui) {
        new_index = ui.newTab.index()+1;
        //do anything
    }
});

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.


In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to tabs

Visual Studio Code - Convert spaces to tabs Sublime Text 3, convert spaces to tabs Bootstrap 3: Keep selected tab on page refresh Change tab bar tint color on iOS 7 Stacked Tabs in Bootstrap 3 C++ printing spaces or tabs given a user input integer Open link in new tab or window How to make a new line or tab in <string> XML (eclipse/android)? Find Active Tab using jQuery and Twitter Bootstrap How to make the tab character 4 spaces instead of 8 spaces in nano?

Examples related to jquery-ui-tabs

jQuery - trapping tab select event jQuery UI Tabs - How to Get Currently Selected Tab Index