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?
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
sort() will sort on the string representation of the Array objects. For instance with two items "Name" and "Name 2" (where text and value are the same) the sort will put "Name" after "Name 2" (because it is actually comparing the strings "Name,Name" and "Name 2,Name 2").
Accepted answer is not the best in all cases because sometimes you want to perserve classes of options and different arguments (for example data-foo).
My solution is:
var sel = $('#select_id'); var selected = sel.val(); // cache selected value, before reordering var opts_list = sel.find('option'); opts_list.sort(function(a, b) { return $(a).text() > $(b).text() ? 1 : -1; }); sel.html('').append(opts_list); sel.val(selected); // set cached selected value
//For ie11 or those who get a blank options, replace html('') empty()
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); });
Here is a working jsfiddle.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With