This is a a recompilation of my 3 favorite answers on this board:
- jOk's best and simplest answer.
- Terry Porter's easy jQuery method.
- SmokeyPHP's configurable function.
The results are an easy to use, and easily configurable function.
First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.
Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.
Sort by text examples (all would sort by text):
sortSelect('select_object_id');
sortSelect('select_object_id', 0);
sortSelect(selectObject);
sortSelect(selectObject, 0);
Sort by value (all would sort by value):
sortSelect('select_object_id', 'value');
sortSelect('select_object_id', 1);
sortSelect(selectObject, 1);
Sort any array by another index:
var myArray = [
['ignored0', 'ignored1', 'Z-sortme2'],
['ignored0', 'ignored1', 'A-sortme2'],
['ignored0', 'ignored1', 'C-sortme2'],
];
sortSelect(myArray,2);
This last one will sort the array by index-2, the sortme's.
Main sort function
function sortSelect(selElem, sortVal) {
// Checks for an object or string. Uses string as ID.
switch(typeof selElem) {
case "string":
selElem = document.getElementById(selElem);
break;
case "object":
if(selElem==null) return false;
break;
default:
return false;
}
// Builds the options list.
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
// allows sortVal to be optional, defaults to text.
switch(sortVal) {
case "value": // sort by value
sortVal = 1;
break;
default: // sort by text
sortVal = 0;
}
tmpAry.sort(function(a, b) {
return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
});
// removes all options from the select.
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
// recreates all options with the new order.
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return true;
}