问题
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>
回答1:
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
来源:https://stackoverflow.com/questions/23907833/sort-options-in-html-select