Sorting a Nested List Using jQuery And Saving the Changes
A reader asked me if it was possible to sort/rearrange items in nested lists (lists within a main list) using the jQuery UI Sortables code. I told him that it was, and I had actually created a tool for a client recently that made use of that feature. He wanted to know more about how to do it, so I went ahead and created a downloadable working demo of how to do it.
You can view an on-line version of the demo (and get the downloadable zip file) here:
The drag-and-drop action that lets you move the items around is the easiest part, as that's simply the Sortables code doing its work. Most of the work involved the code that generates the list for display (written in ColdFusion but do-able in other languages) and the JavaScript code that leverages the core jQuery selectors to scan the list and create a string of data that represents the structure and order of entire list. Both sets of code use a recursive function anytime a nested list is encountered, making it possible to have an unlimited number of nested lists within the main list or any other nested list.
The hierarchy structure is tracked/described through the use of parent ids. Each item in the list has a database record that includes the unique record id of its parent (with items in the main list having a parent id of 0). The JavaScript code records the id of the parent DOM element for each item as it scans the list, and that information becomes part of the string that is submitted via the form. The order of the items is simply the byproduct of the JavaScript code traversing down the list.
Like the tool I wrote for rearranging items in a single list (see related entry), this is simply another means of letting users rearrange the display of records when the order of display can be arbitrary or a matter of preference rather than a strict alphanumeric sort.
