You can sort an array by properties of the objects. Let's consider this sample markup:
<select name="mySelect" id="mySelect>
<option id="opt3" value="val3">Value 3</option>
<option id="opt1" value="val1">Value 1</option>
<option id="opt2" value="val2">Value 2</option>
</select>
And now let's look at a Javascript function that will sort the options of any <select>
:
function sortOptionsByValue(x,y) {
// we are dealing with an options array, so the x and y args
// represent option elements; and we are going to sort by their value
return (x.value == y.value) ? 0 : (x.value > y.value) ? 1 : -1;
}
Then all we have to do is
var mySel = document.getElementById('mySelect');
mySel.options = mySel.options.sort(sortOptionsByValue);
and our options are sorted.
EDITED TO FIX TYPO: mySel.sort => mySel.options.sort