Search code examples
jquery-uijqueryjquery-ui-tabsjquery-tabs

Selecting a jquery-ui-tab based on its id instead of its index?


Anyone know why the following does not work?

$.each( data.d, function( index, item ) {

    // creates the tabs with custom ids
    $( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name )
        .find('>ul>li:last')
        .attr('id', 'tab_' + item.id);

    // creates the buttons
    $( "#buttons" ).append( "<input type='button' id='buttona" + item.id + "' value='" + item.name + "'>" );

    // link buttons with tabs
    $( "#buttona" + item.id ).live('click', function() {
        $( "#tabs" ).tabs( "select" , "#tab_" + item.id );
    });

});

I am trying to assign id's to the tabs, then select the tabs using their id's.

The above does nothing when a button is clicked and it returns no errors at all.

It works fine when using the index as shown below, but I need to use an id for various reasons:

$.each( data.d, function( index, item ) {

    // creates the tabs
    $( "#tabs" ).tabs( "add", "page.aspx?id=" + item.id, item.name );

    // creates the buttons
    $( "#buttons" ).append( "<input type='button' id='button" + index + "' value='" + item.name + "-" + index + "'>" );

    // link buttons with tabs
    $( "#button" + index ).live('click', function() {
        $( "#tabs" ).tabs( "select" , index );
    });

});

Solution

  • You can use the index() method to get the index of the tab from the id of its header:

    $("#button" + item.id).live("click", function() {
        $("#tabs").tabs("select", $("#tab_" + item.id).index());
    });
    

    Since index() is called without arguments in the code above, it will return the index of the element relative to its siblings, i.e. the other tab headers.