3

I can't get jQuery UI tabs to work when dynamically adding tabs and content.

<div id="wrap">
    <ul></ul>
</div>

jQuery

var count = 1;
$('#addspan').click(function() {
    $('#wrap').append('<span id="page' + count + '">testing</span>');
    $('#wrap').find('ul').append('<li><a href="#page' + count + '">' + count + '</a></li>');
    count++;
    $('#wrap').tabs();
});

Check http://jsfiddle.net/qKBUu/1/

You can see that newly created content is not showing in it's respected tabs. All content is showing at once and tabs are not working.

Pinkie
  • 10,126
  • 22
  • 78
  • 124

1 Answers1

6

Try this:

    $(function(){
        var count = 1;

        $('#addspan').click(function() {
            $('#wrap').append('<span id="page' + count + '">testing</span>');
            $('#wrap').find('ul').append('<li><a href="#page' + count + '">' + count + '</a></li>');
            count++;
            var selIndex = $( "#wrap" ).tabs( "option", "selected" );
            $('#wrap').tabs("destroy").tabs({selected: selIndex});
        });
    });

Alternative:

Try $().tabs("add", options...)

e.g:

$(function(){
            var count = 1;
            $('#wrap').tabs();
            $('#addspan').click(function() {
                $('#wrap').append('<span id="page' + count + '">testing</span>');
                //$('#wrap').find('ul').append('<li><a href="#page' + count + '">' + count + '</a></li>');
                $('#wrap').tabs("add","#page" + count, count);
                count++;
            });
        });

Example @: http://jsfiddle.net/Chandu/qKBUu/3/

Chandu
  • 81,493
  • 19
  • 133
  • 134
  • @Pinkie: I think the jQuery tabs tabify's an element once and then allows adding new tabs only via add method. I have checked the jquery.ui.tabs source and looks like there is a _create method and that is called only when the tabs are initially called. I don't have much insight into the widgets extension of jQuery. The only other option is to destroy the tabs and create again. Check my updated post. – Chandu Apr 20 '11 at 21:29
  • jqueryui 1.9 changed api, add method is deprecated: http://jqueryui.com/upgrade-guide/1.9/#deprecated-add-and-remove-methods-and-events-use-refresh-method – Tyler Liu Mar 26 '13 at 05:07