简体   繁体   中英

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,

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;
            });

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)); 
} 

如果你不介意使用jQuery插件, 那么Tablesorter做得很好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM