Forum Moderators: open
Do you generate your options list dynamically on the server (PHP perhaps)...? Then it will be much easier/better/quicker/more accessible to sort them before you create your list in the first place (as you create the HTML to be returned to the browser).
It is possible to sort your HTML options list using JavaScript, but this would be a last resort - it obviously won't be accessible to those with JS disabled. In order to do this, you would need to read through your <option> elements, store them in an array, sort the array and replace all your <option> elements in the DOM with the now sorted elements in the array.
However...
It *could* be argued that this isn't a requirement, and that sorting the array could just be an 'enhancement'. So here's a method that will sort all of the select elements on a page. Note, this example doesn't de-select the original first element of the array, so it ends up still being selected after the sort... but it wouldn't be hard to adjust that behavior.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
</head>
<body>
<form action="">
<div>
<select name="select" size="1">
<option>test</option>
<option>aaa</option>
<option>ccc</option>
<option>ddd</option>
<option>123</option>
</select>
</div>
</form>
<script type="text/javascript">
window.onload = function() {
// Sort ALL select elements
var selectArr = document.getElementsByTagName('select');
for (var i = 0; i < selectArr.length; i++) {
var oArr = [];
// Get the options for the select element
for (var j = 0; j < selectArr[i].options.length; j++) {
// Store this as an object that has an option object member, and
// a toString function (which will be used for sorting)
oArr[oArr.length] = {
option : selectArr[i].options[j],
toString : function() {
// Return the text of the option, not the value
return this.option.text;
}
}
}
// Sort the array of options for this select
oArr.sort();
// Remove all options from the select
selectArr[i].options.length = 0;
// Rebuild the select using our sorted array
for (var j = 0; j < oArr.length; j++) {
selectArr[i].options[j] = oArr[j].option;
}
}
};
</script>
</body>
</html>