jquery-uihtml-listsjquery-ui-tabsjquery-append

tab not working when dynamically added using jquery


i am using the existing jquery UI tabs..

 <div id="tabs">
    <ul>
        <li><a href="#tabs-1">title 1</a></li>
        <li><a href="#tabs-2">title 2</a></li>
        <li><a href="#tabs-3">title 3</a></li>
    </ul>
    <div id="tabs-1">
        <p>t1 content</p>
    </div>
    <div id="tabs-2">
        <p>t2 content</p>
    </div>
    <div id="tabs-3">
        <p>t3 content</p>
    </div>
</div>    

when rendered in the browser, jquery adds some set of classes to the <li> elements. [some part of it given below]

<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" role="tablist">
       <li class="ui-state-default ui-corner-top ui-tabs-active ui-state-active" role="tab" tabindex="0" aria-controls="tabs-1" aria-labelledby="ui-id-1" aria-selected="true" aria-expanded="true">
       <li class="ui-state-default ui-corner-top" role="tab" tabindex="-1" aria-controls="tabs-2" aria-labelledby="ui-id-2" aria-selected="false" aria-expanded="false">
       <li class="ui-state-default ui-corner-top" role="tab" tabindex="-1" aria-controls="tabs-3" aria-labelledby="ui-id-3" aria-selected="false" aria-expanded="false">
</ul>


when I append some <li> elements in <ul> using the following jquery code:

$('#tabs ul').append($('<li><a href="#tabs-4">title 4</a></li>');

The list gets appended but the classes are not added to it, hence do not exhibit the tab functionality.

Please give some insight into it.


Solution

  • You also need to add the div with the tab id:

        var num_tabs = $('div#tabs ul li.tab').length + 1;        
        $('div#tabs ul').append(
            '<li class="tab"><a href="#tab-' + num_tabs + '">Section ' + num_tabs + '</a></li>');
    
        $('div#tabs').append(
            '<div id="tab-' + num_tabs + '"></div>');
    

    Then try a refresh on tabs:

     $("div#tabs").tabs("refresh");
    

    WORKING Fiddle