1

I got a list of names (firstname and lastname) on a page. I want the user to be able to sort this list on either firstname or lastname using jQuery (or normal javascript). How can this be done?

<ul>
<li>Michael Scott</li>
<li>Jonathan Torry</li>
</ul>

Very thankful for all input!

Jonathan Clark
  • 19,726
  • 29
  • 111
  • 175

2 Answers2

4

Array.sort() is what you need

var items = [];
$('ul li').each(function(){
   items.push($(this).html());
})
items.sort();

Example here : http://jsfiddle.net/jomanlk/7UzNZ/

JohnP
  • 49,507
  • 13
  • 108
  • 140
-1

Try my plugin http://www.athos99.com/listorder/type.html

For ordering fistname and lastname, change your list like this :

<ul id="ul1">
<li><span>Michael</span> <span>Scott</span></li>
<li><span>Jonathan</span> <span>Torry</span></li>
</ul>

For ordering by firstname

 $('#ul1').listorder( { child:'li', childValue:function(){return $(this.children([0]).text();} });

For ordering by lastname

 $('#ul1').listorder( { child:'li', childValue:function(){return $(this.children([1]).text();} });


$(this.children([0])   select the 1st span
$(this.children([1])   select the 2nd span
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123