Today I had to do a quick and dirty sort-by-value of the <option />'s in a <select />. I am not proud of having to do this since it should be done on the server-side, but that's a different story.
There are probably a dozen ways to skin this cat, but this is how I did it (I was already using jQuery on this site):
// get the select
var $dd = $('#select-id');
if ($dd.length > 0) { // make sure we found the select we were looking for
// save the selected value
var selectedVal = $dd.val();
// get the options and loop through them
var $options = $('option', $dd);
var arrVals = [];
$options.each(function(){
// push each option value and text into an array
arrVals.push({
val: $(this).val(),
text: $(this).text()
});
});
// sort the array by the value (change val to text to sort by text instead)
arrVals.sort(function(a, b){
return a.val - b.val;
});
// loop through the sorted array and set the text/values to the options
for (var i = 0, l = arrVals.length; i < l; i++) {
$($options[i]).val(arrVals[i].val).text(arrVals[i].text);
}
// set the selected value back
$dd.val(selectedVal);
}
Update (8/20/2009): The above code will only work if the option values are numbers. If the values are alphanumeric and we are doing an alphabetical sort, then the sort function should be replaced with:
arrVals.sort(function(a, b){
if(a.val>b.val){
return 1;
}
else if (a.val==b.val){
return 0;
}
else {
return -1;
}
});

1 Responses to "Sorting (dropdown) Select Options Using jQuery"
Please note that some responses may require approval before appearing.
Chris says:
Thursday, October 23, 2008
Hi , this article is helpful thanks. I wonder if you could suggest the best way to do the following:
Instead of the following:
I need to loop through all the
<options>in a<select>and push them into an array, and just pass that to the function instead of a long string.Eg,
I'd be grateful if you could suggest how to loop through a select element and build an array suitable for this purpose. Thanks.