Append to vertical accordion on button click jquery

766 views Asked by At

I have a horizontal tabs, and inside that, I have a vertical tab functionality. In the vertical tab, I have provided a button called Add More like this:

<button id="addMore" type="button">Add More</button>

On click of the button, I want to append new tab to the previous one.

click method on the button:

$('#addMore').on('click', function() {
    $('#vtabs ul li').last().append('<li><a href="#option1">Option 1</a></li>');
    $('#vtabs div').last().append('<div id="option1">dsg</div>');

    $("#vtabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
    $("#vtabs > ul > li").removeClass("ui-corner-top").addClass("ui-corner-left");
});

Html Part:

<div id = "htabs-outer">
    <h1>htabs-outer</h2>
    <ul>
        <li><a href="#htab-outer-2">Horizontal Tab 2</a></li>
    </ul>

    <div id = "htab-outer-2">
        <h2>Htab outer 2 content</h2>
        <div id="vtabs">
            <h1>Vtabs</h1>
            <ul>
                <li><a href="#vtab-1">Vertical Tab 1</a></li>
                <li><a href="#vtab-2">Vertical Tab 2</a></li>
                <li><a href="#vtab-3">Vertical Tab 3</a></li>
            </ul>
            <div id="vtab-1">
                <h2>Vtab 1 content</h2>
            </div>
            <div id="vtab-2">
                <h2>Vtab 2 content</h2>
            </div>
            <div id="vtab-3">
                <h2>Vtab 3 content</h2>
            </div>
        </div>
        <button id="addMore" type="button">Add More</button>
    </div>
</div>

This does appends to the last li element, but does not function it properly.

I want that if the button is clicked, it should append to the vertical tab and should also append its corresponding div.

What is the mistake that I have made ?

Here's the fiddle that you can have a look at

1

There are 1 answers

0
Rory McCrossan On BEST ANSWER

Firstly, you need to use after() to add the new tab, as append() is placing it inside the existing tab structure, which is incorrect. Secondly, you also need to call refresh on the tabs to add the required styling and events. Try this:

$(function () {
    $("#htabs-outer").tabs();

    var $vtabs = $('#vtabs').tabs().addClass("ui-tabs-vertical ui-helper-clearfix");
    $vtabs.find('> ul > li').removeClass("ui-corner-top").addClass("ui-corner-left");

    $('#addMore').on('click', function () {
        $vtabs
            .find('ul li:last').after('<li><a href="#option1">Option 1</a></li>').end()
            .find('div:last').after('<div id="option1">dsg</div>').end()
            .tabs('refresh').addClass("ui-tabs-vertical ui-helper-clearfix").end()
            .find("> ul > li").removeClass("ui-corner-top").addClass("ui-corner-left");
    });
});

Updated fiddle

Also note that your click handler should be inside the $(function() {}) handler.