10
votes

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.

3
it seems that you have multiple sortable <span>, that certainly will not work as a single group. - Santosh Linkha
@experimentx, yes you can connect multiple spans. Check example here jqueryui.com/demos/sortable/#event-update. Since spans are dynamically added, it doesn't work, otherwise if all were initially in DOM it will work. - Hussein
@Hussein it seems that you are right, i will have a look the code again. - Santosh Linkha
I thought refresh was supposed to refresh dynamically added content but it's not working $('span').sortable('refresh') - Pinkie
shouldn't your <span> be a <div>? or your <div>s be <span>s ? - Walf

3 Answers

10
votes

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.

1
votes

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

0
votes

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