A simpler solution based on Yasser Al-Agl's answer:
function sortList()
{
var lb = document.getElementById('mylist');
arr = new Array();
for(i = 0; i < lb.length; i++) {
arr[i] = lb.options[i];
}
arr.sort(function(a,b) {
return (a.text > b.text)? 1 : ((a.text < b.text)? -1 : 0);
}); // or use localeCompare() if you prefer
for(i = 0; i < lb.length; i++) {
lb.options[i] = arr[i];
}
}
In short, you only need one array, the elements of which simply refer to the original "options" objects. The sort () function also has the right to choose which property of the property to sort (i.e., the text property, the value property, etc.).
Remember, however, that the "selectedIndex" property of the "select" control can no longer be correct after sorting.
source
share