Home > Javascript, Web Design > How to sort a drop down list (select) using jQuery

How to sort a drop down list (select) using jQuery

Let’s assume we have a drop down list that it is initialized to display a list of option and programmatically you want to add or remove options. When you add options you might need to sort options in the drop down list based on the text or the value of each option.

Here is a select box with the list of Cities:

dropdown_list_cities

<select id="cities">
    <option value="0">Select City</option>
    <option value="2">Paris</option>
    <option value="3">London</option>
    <option value="4">Athens</option>
    <option value="5">Mexico</option>
</select>

In order to add a new city, let’s say Rome, and resort them you can do that client side using jQuery:

// Add a last option to the cities drop down list
$("#cities").append($('<option/>').attr('value', '1').text('Rome'));

// Sort by name
$("#cities").html($("#cities option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));

// Sort by Value
// If you don't convert a.value to integers javascript will assume
// that a.value and b.value are strings
$("#cities").html($("#cities option").sort(function (a, b) {
    var aValue = parseInt(a.value);
    var bValue = parseInt(b.value);
    return aValue == bValue ? 0 : aValue < bValue ? -1 : 1;
}));

// Reselect the first option
$('#cities').val('0');

What took me some time to figure out is that the value options should be converted to integers before sorting them as javascript will consider them as strings

Categories: Javascript, Web Design Tags: ,