Select Options Sorting and dropdown Using jQuery

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);
}

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;
}
});

If you have better solution, just tell me !

0 comments: