So I’ve got a list of hidden fields:
<ul class="reorderable">
<li>Foo<input class="hiddenThing" type=hidden name="thing[0]" value=foo /></li>
<li>Bar<input class="hiddenThing" type=hidden name="thing[1]" value=bar /></li>
<li>Baz<input class="hiddenThing" type=hidden name="thing[2]" value=baz /></li>
</ul>
Purely informational, I don’t expect this to be related to the answer, but FYI I’m using the JQuery UI “sortable” plugin:
<script type="text/javascript">
$(document).ready(function () {
$('ul.reorderable').sortable({ update: stuffHappens; });
}
</script>
The thing you need to understand from this is that the sortable plugin allows the user to reorder these elements arbitrarily. Now, what I want to do is implement a revert button.
<button value="Revert" onClick="revertList()" />
I want this to put the elements of the list back in order based on the name of the hidden inputs. I imagine this will require regexes (to extract the number from the brackets in the name. thing[10] should come after thing[9]) and I imagine that JQuery will be handy. But I’m drawing a blank when I try to approach this problem, probably because I’m not familiar with sorting DOM elements nor regexing with JavaScript.
Keeping this naming format is a must.
I’d probably use a standard array sort, then remove all the items and add them back sorted:
Working version here: http://jsfiddle.net/nrabinowitz/Ew2EX/3/
This might get slow if you have a large number of items, but it’s much easier than trying to reorder them in-place.
Code updated to compare single- and double-digit numbers (because
"2">"11").