I'm trying to understand sorting option
elements within a select
element alphabetically. Ideally, I'd like to have this as a separate function where I can just pass in the select element since it needs to be sorted when the user clicks some buttons.
I've searched high and low for a good way of doing this, but haven't been able to find anything that worked for me.
The option elements should be sorted alphabetically by text, not value.
Is this possible in some way?
What I'd do is:
<option>
into an array of objects;<option>
elements with the array contents in order.To do that with jQuery, you could do this:
var options = $('select.whatever option');
var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get();
arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; });
options.each(function(i, o) {
o.value = arr[i].v;
$(o).text(arr[i].t);
});
edit — If you want to sort such that you ignore alphabetic case, you can use the JavaScript .toUpperCase()
or .toLowerCase()
functions before comparing:
arr.sort(function(o1, o2) {
var t1 = o1.t.toLowerCase(), t2 = o2.t.toLowerCase();
return t1 > t2 ? 1 : t1 < t2 ? -1 : 0;
});