Sorting options elements alphabetically using jQuery
html:
<select id="list">
<option value="op3">option 3</option>
<option value="op1">option 1</option>
<option value="op2">option 2</option>
</select>
jQuery:
var options = $("#list option"); // Collect options
options.detach().sort(function(a,b) { // Detach from select, then Sort
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0); // Tell the sort function how to order
});
options.appendTo("#list"); // Re-attach to select
I used tracevipin's solution, which worked fantastically. I provide a slightly modified version here for anyone like me who likes to find easily readable code, and compress it after it's understood. I've also used .detach
instead of .remove
to preserve any bindings on the option DOM elements.
What I'd do is:
- Extract the text and value of each
<option>
into an array of objects; - Sort the array;
- Update the
<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;
});
<select id="mSelect" >
<option value="val1" > DEF </option>
<option value="val4" > GRT </option>
<option value="val2" > ABC </option>
<option value="val3" > OPL </option>
<option value="val5" > AWS </option>
<option value="val9" > BTY </option>
</select>
.
$("#mSelect").append($("#mSelect option").remove().sort(function(a, b) {
var at = $(a).text(), bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
}));
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()