Saving Ordering Of A Sortable List Using jQuery UI
I have a list of items (for brevity, lets call them item1, item2, item3 and item4) which are retrieved from the backend and displayed on a list of sorts.
I wanted to allow the user to update the ordering of these items and that action would automatically update the backend each time there was a change made to the order. So, what I wanted the backend to receive was a comma separated list of IDs of the new sequence/order of the items, similar to
3,2,1,4
Here’s a snippet of the required HTML
<ul id="mylist"> <li id="myItem_1"><img src="icon.png" title="Drag Me" />Item 1</li> <li id="myItem_2"><img src="icon.png" title="Drag Me" />Item 2</li> <li id="myItem_3"><img src="icon.png" title="Drag Me" />Item 3</li> <li id="myItem_4"><img src="icon.png" title="Drag Me" />Item 4</li> </ul>
You will notice that the items have an id with prefix myItem_ followed by the actual numeric ID assigned to those items (by the backend).
Here’s the supporting javascript code using jQuery UI’s sortable feature.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(document).ready(function() { $("#mylist").sortable({ handle : '.handle', update : function () { var newOrdering = $('#mylist').sortable('toArray'); var l = "myItem_".length; var newOrderIds = new Array(newOrdering.length); var ctr = 0; // Loop over each value in the array and get the ID $.each( newOrdering, function(intIndex, objValue) { //Get the ID of the reordered items //- this is sent back to server to save newOrderIds[ctr] = objValue.substring(l,objValue.length); ctr = ctr + 1; } ); alert("newOrderIds : "+newOrderIds); //Remove after testing $("#info").load("save-item-ordering.jsp?"+newOrderIds); } }); }); |
Notice line 15
15 | newOrderIds[ctr] = objValue.substring(l,objValue.length); |
The objValue looks like myItem_1, where 1 is the ID assigned to an item by the backend. This is why the the ID is being extracted out by the above line of code.
Credits: