I have a list made as sortable using jQuery UI. The first list item is “Item 1”, second is ‘Item 2” like that. My requirement is the list items must be initialized based
I don't think the sortable plugin comes with an option to set the initial order of the elements. I think it expects the elements to be initially rendered in the correct order (which makes sense in my opinion - why don't you do that ?)
Anyway, here's a piece of code that will sort the elements prior to initializing the sortable plugin:
var arrValuesForOrder = ["3", "1", "4", "2"];
var $ul = $("#myUnorderedList"),
$items = $("#myUnorderedList").children();
// loop backwards so you can just prepend elements in the list
// instead of trying to place them at a specific position
for (var i = arrValuesForOrder[arrValuesForOrder.length - 1]; i >= 0; i--) {
// index is zero-based to you have to remove one from the values in your array
$ul.prepend( $items.get(arrValuesForOrder[i] - 1));
}
$("#myUnorderedList").sortable({
axis: 'y',
handle: '.handle',
update: function() {
var order = $('#myUnorderedList').sortable('serialize');
alert(order);
}
});
DEMO
I solved it this way using 3 sortable and ordering them by the id of the html element
Why do you want to store the pre-order in JS? If it is hardcoded HTML, why don't you change the HTML? And if you use a scripting language, why don't you use that to pre-order?
I'm not sure if sortable
has triggers to move items, but either way it would not be a good idea to do that after initialization of your script, because the items will load as 1,2,3,4 and then on document.ready rearrange..