Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting options elements alphabetically using jQuery

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?

like image 693
bomortensen Avatar asked Aug 22 '12 12:08

bomortensen


People also ask

How do I sort alphabetically in JavaScript?

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.

How do you sort options in JavaScript?

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").


2 Answers

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()

like image 44
marxin Avatar answered Oct 02 '22 01:10

marxin


What I'd do is:

  1. Extract the text and value of each <option> into an array of objects;
  2. Sort the array;
  3. 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; }); 
like image 183
Pointy Avatar answered Oct 02 '22 02:10

Pointy