jQuery-ui Sortable gotcha! serialize() method was returning empty
I cobbled together a quick demo of jQuery sortable for a todo quick and dirty todo-list for the websites I maintain. In an attempt to come up with minimal code to demo the jQuery sortable element, I came up with the following. The following code is best ran through firebug with a console enabled to be able to see the update messages. Also, the jquery.js and jquery-ui.js are symlinks to jquery-1.3.2.min.js and jquery-ui-1.7.2.custom.min.js which can be downloaded from jquery.com
<html>
<head>
<title>To Do</title>
<script src="jquery.js"> </script>
<script src="jquery-ui.js"> </script>
<script type="text/javascript">
$(document).ready( function () {
$("#alist").sortable({
update: function () {
var orderx=$("#alist").sortable('serialize');
console.log( 'orderx is '+orderx );
}});
});
</script>
</head>
<body>
<ul id="alist">
<li id="item_1">First Item</li>
<li id="item_2">Second Item</li>
<li id="item_3">Third Item</li>
<li id="item_4">Last Item</li>
</ul>
</body>
</html>
It is important that the ids for the <li> elements are set. and that the value of the id must have an underscore. This is necessary for the serialize method to work. Thus, item_1 will work, while item1 will not. It took me 35 minutes to carefully read through the docs and flail a bit to figure this out.
The portion of the id before the underscore is used as a variable name, in this instance: item. When you run through this a few times, you’ll get the following console output:
orderx is item[]=4&item[]=1&item[]=2&item[]=3
This string can then be passed as part of a URL for a server-side script to do with as it pleases. In my case, I intend to persist the ordering. Thus, there are N * M databases update statements where N is the length of the list and M is the number of times a given list element is moved. Quite inefficient, but we’ll tackle that in another post.