1

I have two lists. The goal is to drag items from the first list into the second list. I have stored the correct order in the data attribute.

<ul class="connectedSortable ui-sortable" id="sortable1">
<li data-pos="4" class="ui-sortable-handle">item a</li>
<li data-pos="3" class="ui-sortable-handle">item b</li>
<li data-pos="1" class="ui-sortable-handle">item c</li>
<li data-pos="2" class="ui-sortable-handle">item d</li>
<li data-pos="5" class="ui-sortable-handle">item e</li>
<li data-pos="6" class="ui-sortable-handle">item f</li>
</ul>

<ul class="connectedSortable ui-sortable" id="sortable1">
<li data-pos="0" class="ui-sortable-handle">top item</li>
<li data-pos="7" class="ui-sortable-handle">bottom item</li>
</ul>

When the second list is changed, I loop over the items to see if they are in the correct order:

$("#sortable2").sortable({
    change: function () {
        var solved = false;
        console.log("-----------");
        //:not(.ui-sortable-placeholder)
        $.each($("#sortable2 .ui-sortable-handle"), function (key, val) {
            console.log("item key: " + key + " - data: " + $(val).data('pos'));
        });
    }
});

When I drag the first item over, the output will read:

item key: 0 - data: 0
item key: 1 - data: undefined
item key: 2 - data: 8

But I can see in the source code that there are three items in the list. Subsequent drag&drops will show the correct index, with the first still not showing in the loop. I tried to exclude the placeholder from the loop, with no luck.

1
  • Both the ul> in given markup has the same id of sortable1 and in script you've specified #sortable2 Obviously it'll not work as well as it's invalid markup. I wonder how you're saying it's working..! Commented Nov 1, 2014 at 16:51

1 Answer 1

1

From the docs:

Change

This event is triggered during sorting, but only when the DOM position has changed.

(emphasis mine)

When you hover over the second sortable, the placeholder is insert into it, changing the position of it's sortable items in DOM which in turn triggers change -

The placeholder does not have the data associated, so it prints undefined. If you exclude the placeholder from iteration, then it'll print the data of remaining items, which is expected.


If you're trying to get the data of new items after drop or re-arrangement, you should use the update event instead (of course exclude the placeholder since that's not out guy :)

Updated Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.