Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.sortable. change the order by JavaScript

How can I change the order of a list once applied by JavaScript jQuery.sortable.

For example:

<ul id="mylist">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>
var x_sortable_list = $("mylist").sortable();

Then, assuming this to work:

x_sortable_list.changeOrder([
 {item:1, newOrder:2 },
 {item:2, newOrder:1 },
 {item:3, newOrder:3 }
]);
like image 877
andres descalzo Avatar asked Jan 14 '10 21:01

andres descalzo


3 Answers

Like others have mentioned, this has nothing to do with the sortable() functionality. Instead you need to retrieve the items in the list, shift their positions and then clear and re-insert the list items again in their new order:

// Get your list items
var items = $('#mylist').find('li');

// The new index order for each item
var order = [4, 2, 0, 1, 3];

// Map the existing items to their new positions        
var orderedItems = $.map(order, function(value) {
    return items.get(value);
});

// Clear the old list items and insert the newly ordered ones
$('#mylist').empty().html(orderedItems);
like image 72
Lance McNearney Avatar answered Nov 14 '22 08:11

Lance McNearney


As Sparr has said, there's no way to sort them using sortable directly, but you can still move them manually with something like:

$("#mylist li:eq(1)").insertAfter($("#mylist li:eq(2)"));
like image 11
Alconja Avatar answered Nov 14 '22 10:11

Alconja


The sortable provides a user interface for rearranging the items. To rearrange them programmatically you still need to manipulate the elements yourself, manually or with some other plugin.

like image 1
Sparr Avatar answered Nov 14 '22 08:11

Sparr