Aug 19

Sorting (dropdown) Select Options Using jQuery

A snippet of JavaScript to sort a select dropdown using jQuery

Today I had to do a quick and dirty sort-by-value of the <option />'s in a <select />. I am not proud of having to do this since it should be done on the server-side, but that's a different story.

There are probably a dozen ways to skin this cat, but this is how I did it (I was already using jQuery on this site):

// get the select
var $dd = $('#select-id');
if ($dd.length > 0) { // make sure we found the select we were looking for

    // save the selected value
    var selectedVal = $dd.val();

    // get the options and loop through them
    var $options = $('option', $dd);
    var arrVals = [];
    $options.each(function(){
        // push each option value and text into an array
        arrVals.push({
            val: $(this).val(),
            text: $(this).text()
        });
    });

    // sort the array by the value (change val to text to sort by text instead)
    arrVals.sort(function(a, b){
        return a.val - b.val;
    });

    // loop through the sorted array and set the text/values to the options
    for (var i = 0, l = arrVals.length; i < l; i++) {
        $($options[i]).val(arrVals[i].val).text(arrVals[i].text);
    }

    // set the selected value back
    $dd.val(selectedVal);
}


Update (8/20/2009): The above code will only work if the option values are numbers. If the values are alphanumeric and we are doing an alphabetical sort, then the sort function should be replaced with:

arrVals.sort(function(a, b){
    if(a.val>b.val){
        return 1;
    }
    else if (a.val==b.val){
        return 0;
    }
    else {
        return -1;
    }
});

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top