Getting the position of the element in a list when it's drag/dropped (ui.sortable)
12,322
Solution 1
SOLUTION:
$(function() {
$('ul#sortable').sortable({
start: function(event, ui) {
var start_pos = ui.item.index();
ui.item.data('start_pos', start_pos);
},
update: function(event, ui) {
var start_pos = ui.item.data('start_pos');
var end_pos = ui.item.index();
alert(start_pos + ' - ' + end_pos);
}
});
});
Solution 2
I believe what you are looking to do is done with the serialize method. Serialize is get the new order of the list.
Solution 3
For some reason ui.item.index()
did not work for me.
This did:
update: function (event, ui)
{
var index = $('li', $(ui.item).parent()).index(ui.item);
alert(index);
}
Related videos on Youtube
Author by
Wurlitzer
Updated on April 16, 2022Comments
-
Wurlitzer about 2 years
I have a sortable list like this one: http://jqueryui.com/demos/sortable
Is it possible to get the start and end position of the element in the list, when it has been moved? I'm talking about their position number, in the list.
For example, if I move element 2 to position 5 in the list, I'd like to assign those two numbers to variables.
I'm new to jQuery - any help would be much appreciated.
-
Marijn Huizendveld about 13 yearsThis is such a great example of the terrible API design of jQuery UI
-
-
Mottie about 14 years+1 Nice concise answer, but you don't need to wrap the
ui.item
, it's already a jQuery object. So instead of$(ui.item)
useui.item
-
Wurlitzer about 14 yearsElegant answer! Thank you so much. I guess the ui.item object is what I was looking for, here.
-
Alconja over 13 years+1, although you should probably use
ui.item.data('start_pos', start_pos);
instart
andvar start_pos = ui.item.data('start_pos');
inupdate
rather than polluting theid
.