Pinkie
Pinkie

Reputation: 10256

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.

Upvotes: 10

Views: 24361

Answers (3)

Rahul Varadkar
Rahul Varadkar

Reputation: 258

Change Button Click event as given below, and it works. No other changes are required. I tried in jfiddler and it worked. Newly added items becomes part of list and are sortable as well.

$('button').click(function() {
    var x = $('<div>aaaaaaaaa</div>');
    x.appendTo('#form .con')
});

I defined x as element and further x is appenedTo ".con" class inside #form.

The screen-shot of this updated example is shown below:

enter image description here

Upvotes: 0

Nick
Nick

Reputation: 11

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

Upvotes: 1

S L
S L

Reputation: 14328

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.

Upvotes: 11

Related Questions