0

There is situation like this:

<select id="trollSelect">
    <option value="PL">Polish Troll</option>
    <option value="EN">English Troll</option>
    <option value="JP">Japanese Troll</option>
    [...] //more options created dynamically
</select>

Option values and Option texts are unsorted in Select. Is this possible to sort this options in JQuery or Javascript by value or text alphabetically ??

The result should be like that:

<select id="trollSelect">
    <option value="EN">English Troll</option>
    <option value="JP">Japanese Troll</option>
    <option value="PL">Polish Troll</option>
    [...] //more options created dynamically
</select>
user3383675
  • 1,041
  • 5
  • 12
  • 31

1 Answers1

5

This code should do it. I've sorted them on their values but this can also be used to sort based on the text.

$(document).ready(function() {
    var opt = $("#trollSelect option").sort(function (a,b) { return a.value.toUpperCase().localeCompare(b.value.toUpperCase()) });
    $("#trollSelect").append(opt);
});

Here's a fiddle for the same

Samy S.Rathore
  • 1,825
  • 3
  • 26
  • 43