kevinabraham kevinabraham -4 years ago 157
Javascript Question

How to get jQuery sortable list order?

I am using jQuery Sortable to allow users to drag and drop elements on the page. When a user drags a div I need to get the updated order of the list and pass it to the back end. So far I've tried:

$( function() {
$( "#sortable" ).sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
data: oData,
type: 'POST',
url: '/url/here'
$( "#sortable" ).disableSelection();
} );

but this makes the animation really not smooth and alerts no data. How do I get a position list every time a user drags and drops a div?


Answer Source

There's a refreshPositions() function you can use that returns a object representing the sortable item. You can then obtain the updated list of children by making a call to .children() on that object.

Save the positions to a variable in the stop event, which is triggered after you have finished sorting.

I've updated your function to include the stop event:

  stop: function(ev, ui) {
    //Get the updated positions by calling refreshPositions and then .children on the resulting object.
    var children = $('#sortable').sortable('refreshPositions').children();
    console.log('Positions: ');
    //Loopp through each item in the children array and print out the text.
    $.each(children, function() {

Updated Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download