Sorting HTML Option lists with jQuery
I’ve recently been working on a WordPress plugin for a client that includes the ability to filter the results via multiple select boxes, with the contents of the select boxes themselves filtered so only the relevant options are shown.
It’s a nice little solution that I’d love to show off, but alas, I’m NDA’s and can’t talk about work for that client.
What I can share though is a neat little solution for sorting the contents of select lists alphabetically. It’s borrowed from elsewhere on the web, so not my own work, but useful nonetheless.
var options = $('select.whatever option');
var arr = options.map(function(_, o) {
return {
t: $(o).text(),
v: o.value,
s: $(o).prop('selected')
};
}).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);
$(o).prop('selected', arr[i].s);
});