Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text, value, and selected properties, but I don't think that javascript's built in Array.sort() would work correctly.

like image 923
travis Avatar asked Sep 05 '08 14:09

travis


People also ask

How do you sort values in HTML?

How to Make Sortable Tables. Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work.

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

Extract options into a temporary array, sort, then rebuild the list:

var my_options = $("#my_select option"); var selected = $("#my_select").val();  my_options.sort(function(a,b) {     if (a.text > b.text) return 1;     if (a.text < b.text) return -1;     return 0 })  $("#my_select").empty().append( my_options ); $("#my_select").val(selected); 

Mozilla's sort documentation (specifically the compareFunction) and Wikipedia's Sorting Algorithm page are relevant.

If you want to make the sort case insensitive, replace text with text.toLowerCase()

The sort function shown above illustrates how to sort. Sorting non-english languages accurately can be complex (see the unicode collation algorithm). Using localeCompare in the sort function is a good solution, eg:

my_options.sort(function(a,b) {     return a.text.localeCompare(b.text); }); 
like image 183
Mark Avatar answered Oct 01 '22 13:10

Mark


Modified Tom's answer above slightly so that it actually modifies the contents of the select box to be sorted, rather than just returning the sorted elements.

$('#your_select_box').sort_select_box(); 

jQuery function:

$.fn.sort_select_box = function(){     // Get options from select box     var my_options = $("#" + this.attr('id') + ' option');     // sort alphabetically     my_options.sort(function(a,b) {         if (a.text > b.text) return 1;         else if (a.text < b.text) return -1;         else return 0     })    //replace with sorted my_options;    $(this).empty().append( my_options );     // clearing any selections    $("#"+this.attr('id')+" option").attr('selected', false); } 
like image 31
JaredC Avatar answered Oct 01 '22 13:10

JaredC