views:

411

answers:

2

Hi all

I have a Listbox with some items on a page. Is there any simple way to sort the items using Jquery or native javascript?

Best Regards,

A: 

If you don't mind using a jQuery plug-in, Tablesorter does a good job.

Ken Redler
+1  A: 

You can use a Javascript JQuery function as below. I havent tested it fully but must 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 Select Tag should have an Id MySelect. You can also do this using plain javascript.This will sort by the Displayed Text of the Options.Instead if you want to sort by the Value of each option . You use a sort as below

 $r.sort(function(a, b) {
               return a.value-b.value;
            });
josephj1989