Tuesday, December 2, 2014

Select tab by its name to display as active for jQuery Tabs widget

There is a widget in the jQuery UI library known as "Tabs". Quite simply, it can be used to display tables in multiple tabs. I had the opportunity to figure out how to programmatically trigger a specific tab to be the currently active one to be displayed.

Here's what you need
  • the use of Active option
  • locating the tab by name like this
The HTML snippet is as follows:

<div id="tabs">

  <ul>
   <li><a href="#actionTab1"><span>One</span></a></li>
   <li><a href="#actionTab2"><span>Two</span></a></li>
   <li><a href="#actionTab3"><span>Three</span></a></li>
 </ul>
</div>
The script snippet is as follows:
<script>
//search tab index for value matching specific tab
var displayTab = $('#tabs a[href="#actionTab2"]').parent().index();
$("#tabs").tabs({active: displayTab});
</script>


In accommodating our server-side logic, a modification was done thus,

//variable set from server

var displayTab = $('#tabs a[href="#${svTab}"]').parent().index();

And because it may fail to find the item and return -1,

var displayTab = $('#tabs a[href="#actionTab2"]').parent().index();

if(displayTab == -1) {
  displayTab = 0; //default to first tab
}


"A negative value selects panels going backward from the last panel."

The final version I used:

<script>
//search tab index for value matching specific tab
var displayTab = $('#tabs a[href="#${svTab}"]').parent().index(); 

if(displayTab == -1) {
  displayTab = 0; //default to first tab
}
$("#tabs").tabs({active: displayTab});

</script>

In short:
  1. Identify the <div> of the tab heading,
  2. Filter for its <a> children with the matching href attribute,
  3. Return the (zero-based) index of the parent <li>
  4. Create a JSON object setting the index into the name "active"
  5. Call the widget with the JSON object as the argument
It is possible to simply call Tabs with {active: 1} but I felt that it was more readable to be able to search and set the index value according to the tab name instead, so that it can work even if the tab items get rearranged.

And that was it. Have fun!

No comments:

Post a Comment