1

I am looking for an algorithm that will sort option values alphabetically.

$(this).html($("option", $(this)).sort(function(a, b) { 
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1 
}));

With this above code it appears that its working, however as soon as I introduce multiple works, sorting becomes unpredictable.

Let say or example I am trying to sort this:

<select class='whatever'>
    <option value='Lorem dva'>Lorem dva</option>
    <option value='a1'>a1</option>
    <option value='pl1'>pl1</option>
</select>

I am using jQuery.

Thank you!

Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46
Toniq
  • 4,492
  • 12
  • 50
  • 109
  • possible duplicate of [What is the easiest way to order a
      /
      in jQuery?](http://stackoverflow.com/questions/304396/what-is-the-easiest-way-to-order-a-ul-ol-in-jquery)
    – dtech Dec 13 '13 at 19:37

1 Answers1

2

Your example is already sorted, because capital 'L' goes before 'a' in ASCII. Maybe you want to add toLowerCase()?

And you should re-insert sorted options into the DOM:

$(document).ready(function () {
    $(this).html($("option", $(this)).sort(function (a, b) {
        return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
    }).appendTo(".whatever"));
});

http://jsfiddle.net/5zpTu/3/

Sergii Dymchenko
  • 6,890
  • 1
  • 21
  • 46