How do I sort a drop down list in HTML?

How TO - Sort a List

❮ Previous Next ❯


Learn how to sort an HTML list, using JavaScript.


Click the button to sort the list alphabetically:

Sort
  • Oslo
  • Stockholm
  • Helsinki
  • Berlin
  • Rome
  • Madrid

Try it Yourself »


How to sort dropdown list items in jQuery?

JS

  1. $(function() {
  2. // choose target dropdown.
  3. var select = $(‘select’);
  4. select. html(select. find(‘option’). sort(function(x, y) {
  5. // to change to descending order switch “<” for “>”
  6. return $(x). text() > $(y). text()? 1 : -1;
  7. }));

How do I sort alphabetically in drop down?

Creating the Drop Down List

  1. Select the range of cells where we wish the drop down list to appear, and then in the Ribbon, select Data > Data Validation.
  2. Now select List from the Allow list, then type the formula for the Source of the list.
  3. Click OK to create the sorted drop down list in the selected range.

Sort Dropdown list items using jQuery

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:

  • 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.


Scripts Used on This Site