In this post, find out jQuery code to sort dropdown list items. The items can be sorted by item's text or by item's value in ascending or descending order.
Related Post:
To sort the items, use JavaScript sort method. Sort method takes sortfunction as parameter which defines the sort order. Below jQuery code sorts the dropdown list items by their text in ascending order.
You can also sort the items by their value in ascending order. While comparing the values in sort function use val() method, instead of text().
Related Post:
- Common Dropdown operation using jQuery
- How to Reset DropDown using jQuery
- How to Disable DropDown List Item using jQuery
To sort the items, use JavaScript sort method. Sort method takes sortfunction as parameter which defines the sort order. Below jQuery code sorts the dropdown list items by their text in ascending order.
$('#btnSort').click(function(e) { $("#ddlList").html($('#ddlList option').sort(function(x, y) { return $(x).text() < $(y).text() ? -1 : 1; })) $("#ddlList").get(0).selectedIndex = 0; e.preventDefault(); });See result below
You can also sort the items by their value in ascending order. While comparing the values in sort function use val() method, instead of text().
$('#btnSort').click(function(e) { $("#ddlList").html($('#ddlList option').sort(function(x, y) { return $(x).val() < $(y).val() ? -1 : 1; })) $("#ddlList").get(0).selectedIndex = 0; e.preventDefault(); });Above both jQuery code sorts the items in ascending order. If you want to sort them in descending order then just need to make a small change. Instead of using "<" then sign,
return $(x).val() < $(y).val() ? -1 : 1;Use ">" sign for comparison and it will sort the items in descending order.
return $(x).val() > $(y).val() ? -1 : 1;
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.
No comments:
Post a Comment