Chetan Chauhan
Chetan Chauhan

Reputation: 33

jQuery UI sortable for dynamically added items

I have HTML markup where by clicking on an add row button, then a visually hidden HTML element which is sibling to the add new button gets cloned and inserted before it.

<div class='wrapper'>
<div class="container">
    <div class="sortable">
        <div class="ui-state-default">
            <div class="container">
                <div class="sortable">
                    <div class="ui-state-default">Item 1</div>
                    <div class="ui-state-default">Item 2</div>
                    <div class="ui-state-default hidden">Hidden</div> <a href="#" class="add-button"> Add New Sub </a>

                </div>
            </div>
        </div>
        <div class="ui-state-default hidden">
            <div class="container">
                <div class="sortable">
                    <div class="ui-state-default">Item 1</div>
                    <div class="ui-state-default">Item 2</div>
                    <div class="ui-state-default hidden">Hidden</div> <a href="#" class="add-button"> Add New Sub </a>

                </div>
            </div>
        </div> <a href="#" class="add-button"> Add New </a>

    </div>
</div>

Here is JS code:

function sortableInit(container) {
container.find('.sortable').sortable({
    axis: 'y',
    cursor: 'move',
    items: '> .ui-state-default',
});
}
$(function () {
$(".container").each(function () {
    sortableInit($(this));
});
$('.wrapper').on('click', '.add-button', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var hidden = $(e.target).siblings('.hidden').clone(true).removeClass('hidden');
    hidden.insertBefore($(e.target));
});
});

Here is the jsfiddle link, giving much closer idea of what I am trying to do.

When you run the jsfiddle, click on the Add New button, for the newly added element, try to sort the element Item 1 and Item 2. Although they can be dragged, but cannot be sorted.

Note: The div.ui-state-default element can contain div.container element upto any depth level(nested repeatable field groups).

Upvotes: 2

Views: 1289

Answers (1)

Josh Burgess
Josh Burgess

Reputation: 9567

You're making it more complicated than it needs to be. Rather than trying to do a deep clone (.clone(true)), just call the sortableInit() on the cloned item.

JSFiddle Example

$('.wrapper').on('click', '.add-button', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var hidden = $(e.target).siblings('.hidden').clone().removeClass('hidden'); //Removed 'true' from clone
    hidden.insertBefore($(e.target));
    sortableInit(hidden); //This added.
});

Upvotes: 2

Related Questions