dropdown-sort

Sort Select list items using jQuery

In this Article, you find out jQuery code to sort dropdown list items. The items can be sorted by item’s text and also by item’s value in ascending or descending order.

First create dropdown list items in html

<select id="ddlList">
  <option value="3">Three</option>
  <option value="1">One</option>
  <option value="0">Zero</option>
  <option value="2">Two</option>
  <option value="8">Eight</option>
</select>
<br/><br/>
<input type="button" id="btnSort" Value="Sort Dropdown By Text" />
<input type="button" id="btnSortVal" Value="Sort Dropdown By Value" />

With above html code we create dropdown list.
to give it style to look nice

body
{
    padding: 10px;
    font-family:Calibri;
    font-size: 12pt;
}
input
{
    font-family:Calibri;
    font-size: 12pt;
}
select
{
    font-family:Calibri;
    font-size: 12pt;
    color: Black;
    background-color: Lightblue;
}

To sort the items, use Jquery sort method. Sort method takes sort function 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 ”

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;

Feel free to contact me for any help related to jQuery, I will gladly help you.

Related Posts


2 thoughts on “Sort Select list items using jQuery

  1. system ear plugs jewelry 0g

    I’ve found this new technology and health article site. It’s got some helpful articles.

    Reply
  2. Dominio para un sitio web

    Wow, awesome weblog layout! How lengthy have you ever been blogging for? you make running a blog glance easy. The entire look of your website is magnificent, as smartly as the content material!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *


*