Sorting ListBox Items Using Javascript / JQuery

I have a Listbox with some items on the page. Is there an easy way to sort items using jQuery or native javascript?

Best wishes,

+7
javascript jquery
source share
3 answers

You can use Javascript jQuery as shown below. I have not tested it completely, but it should work.

function Sortit() { var $r = $("#MySelect option"); $r.sort(function(a, b) { if (a.text < b.text) return -1; if (a.text == b.text) return 0; return 1; }); $($r).remove(); $("#MySelect").append($($r)); } 

Here, your selected tag should have the identifier MySlelect. You can also do this using simple javascript. This will sort by the displayed text of the parameters. Instead, if you want to sort by the value of each parameter, you use the sort below

  $r.sort(function(a, b) { return a.value-b.value; }); 
+14
source share

I used a method very similar to @ josephj1989. However, if there are values ​​as values ​​in the drop-down list, you still need to assign the values ​​1, -1, or 0 (at least I did this).

 function SortList(listname) { var $r = $(listname + " option"); $r.sort(function(a, b) { return (a.value < b.value) ? -1 : (a.value > b.value) ? 1 : 0; //or you can have a.text, b.text, etc }); $($r).remove(); $(listname).append($($r)); } 
+1
source share

If you don't mind using the jQuery plugin , Tablesorter does a good job.

0
source share

All Articles