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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With