User Tools

Site Tools


jquery:select-ui-tab-by-id-and-index

jQuery select UI tabs by id (and index)

With the latest versions of jQuery is not not trivial to select a tab by ID as it was before.

Previously you could use:

$("#tabs").tabs("select", "#tab-1");

now is more difficult since that function has been deprecated and the ufficial method is only

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

where index is the ordinal number counting tabs from left to right.

Now, if you can be sure the index never change you can use

$(mytabs).tabs("option", "active", $("#tab_header").index());

but if the number of tabs change it needs a specific function intended to iterate the tabs, incrementing an index of the tabs counted before reaching the id we were looking for.

This is the function.

id2index.js
//tabsId Id of the div containing the tab code.
//srcId Id of the tab whose id you are looking for
function id2Index(tabsId, srcId)
{
	var index=-1;
	var i = 0, tbH = $(tabsId).find("li a");
	var lntb=tbH.length;
	if(lntb>0){
		for(i=0;i<lntb;i++){
			o=tbH[i];
			if(o.href.search(srcId)>0){
				index=i;
			}
		}
	}
	return index;
}

So, having something such as

<div id="tabs">
    <ul>
        <li><a href="#tab-1"><span>One</span></a></li>
        <li><a href="#tab-3"><span>Two</span></a></li>
        <li><a href="#tab-6"><span>Three</span></a></li>
    </ul>
</div>

you can activate #tab-6 with

$("#tabs").tabs("option","active", id2Index("#tabs","#tab-6"));

How does it works?

I read the tabs “a href” and get the ID from there. When it is found in the loop, I read the id that jQuery add automatically for every tab into the dom when the UI tabs is initialized.

jquery/select-ui-tab-by-id-and-index.txt · Last modified: 2014/09/03 19:46 by rik