Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery using Sortable with dynamically added elements (live refresh)

I have a <form id="#form"> that have a <span class="con"> and inside the span i have many divs that needs to be sortable.

<form id="form">
    <span class="con">
        <div class="ui-state-highlight">Item 1</div>
        <div class="ui-state-highlight">Item 2</div>
        ... 
    </span>
</form>

I'm using the sortable function to make div Sortable.

$("span").sortable({
    connectWith: ".con"
}).disableSelection();

I'm dynamically adding with divs inside. But sortable is not recognizing newly added spans. I know there's a refresh option for sortable that is supposed to work like live() and reognize newly added content, but i don't see how i can use it with this example.

Check http://jsfiddle.net/mRyVp/8/. Click on the button to add more spans with divs inside. You will see that you can sort div that were initially in DOM but not newly added ones.

like image 564
Pinkie Avatar asked Mar 29 '11 05:03

Pinkie


2 Answers

It seems that you have class="connectedSortable" in

<span class="connectedSortable">
    <div class="ui-state-highlight">Item 1</div>
    <div class="ui-state-highlight">Item 2</div>
    ... 
</span>

And connectWith: ".con" in

$("span").sortable({
    connectWith: ".con"
}).disableSelection();

Adding con class to original div will just be fine. Update here.

like image 135
Santosh Linkha Avatar answered Oct 22 '22 04:10

Santosh Linkha


Try this:

$('button').click(function() {
    var x = $('<div class="ui-state-highlight">Item '+($('.con div').length+1)+'</div>');
    x.appendTo('#form .con')
});

$("span").sortable({
    connectWith: ".con"
}).disableSelection();

When you click over 'add another option', the script will add new sortable 'Item' into the list

like image 23
Nick Avatar answered Oct 22 '22 04:10

Nick