views:

10035

answers:

3

I'm a bit out of my depth here and I'm hoping this is actually possible.

I'd like to be able to call a function that would sort all the items in my list alphabetically.

I've been looking through the jQuery UI for sorting but that doesn't seem to be it. Any thoughts?

+30  A: 

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. http://plugins.jquery.com/project/TinySort

SolutionYogi
excellent! just what i needed
Andrew Bullock
Can the last line be replaced with $(listitems).appendTo(mylist); ?
Amir
me too, thanks!!
ina
+9  A: 
Josh Stodola
A: 

Thanks for the sort function!

Andy
Please use comments for this, not answers.
Josh Stodola