Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ListBox items using Javascript/Jquery

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,

like image 539
Yongwei Xing Avatar asked Jun 03 '10 02:06

Yongwei Xing


2 Answers

You can use a Javascript JQuery function as below. I haven't tested it fully but it 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;
            });
like image 176
josephj1989 Avatar answered Sep 30 '22 00:09

josephj1989


I used a method very similar to @josephj1989. However, if your dropdown has strings as values, you still need to assign the 1, -1, or 0 values (at least I did anyway).

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)); 
} 
like image 29
WEFX Avatar answered Sep 29 '22 23:09

WEFX