I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text
, value
, and selected
properties, but I don't think that javascript's built in Array.sort()
would work correctly.
views:
5003answers:
4Well, in IE6 it seems to sort on the nested array's [0] item:
function sortSelect(selectToSort) {
var arrOptions = [];
for (var i = 0; i < selectToSort.options.length; i++) {
arrOptions[i] = [];
arrOptions[i][0] = selectToSort.options[i].value;
arrOptions[i][1] = selectToSort.options[i].text;
arrOptions[i][2] = selectToSort.options[i].selected;
}
arrOptions.sort();
for (var i = 0; i < selectToSort.options.length; i++) {
selectToSort.options[i].value = arrOptions[i][0];
selectToSort.options[i].text = arrOptions[i][1];
selectToSort.options[i].selected = arrOptions[i][2];
}
}
I'll see if this works in other browsers...
Edit: it works in Firefox too, woo hoo!
Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?
Array.sort()
defaults to converting each element to a string, and comparing those values. So ["value", "text", "selected"]
gets sorted as "value, text, selected"
. Which will probably work fine, most of the time.
If you do want to sort on value alone, or interpret value as a number, then you can pass a comparison function into sort():
arrOptions.sort(function(a,b) { return new Number(a[0]) - new Number(b[0]); });
There's a closed jQuery ticket for a sort that should work, but just wasn't included in the core.
jQuery.fn.sort = function() {
return this.pushStack( [].sort.apply( this, arguments ), []);
};
Referenced from a Google Groups thread, I think you just pass in a function that is used to sort, like so
function sortSelect(selectToSort) {
jQuery(selectToSort.options).sort(function(a,b){
return a.value > b.value ? 1 : -1;
});
}
Hope it helps!
bdukes I like your answer but it would not sort a select list in place for me?
Instead the options had to be pulled into a temporary array, sorted, then the list rebuilt:
var my_options = $("#my_select option");
my_options.sort(function(a,b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
else return 0
})
$("#my_select").empty().append( my_options );