Sorting a SELECT with JQuery

Just a simple function to sort an already populated list. Obviously it would be easier to sort before populating, but there are the odd occasion where this is more complicated than you thought.

Requirements : JQuery

var selectOptions = $("#selectId option");

Then, we just run the sort command on the options array – and this easily sorts the items.

selectOptions.sort(function(a, b) {
    if (a.text > b.text) {
        return 1;
    }
    else if (a.text < b.text) {
        return -1;
    }
    else {
        return 0
    }
});

Then, at the end empty the select object and re-append the sorted options array

$("#selectId").empty().append(selectOptions);

Note. I just found a problem with this. If you have already selected an option, that selection will be lost unless you save the selection value before sorting and replace it at the end:

var selectedOption = $('#selectId').val();

And then to restore it

$('#selectId').val(selectedOption);

3 comments on “Sorting a SELECT with JQuery

  1. Phil De Caux September 1, 2011 3:55 pm

    Brilliant! I turned it into a function so I can sort any select list:

    function sort_list(select_id) {
    // based on: http://www.christatedavies.co.uk/2010/10/04/sorting-a-select-with-jquery/
    var selectOptions = $(“#”+select_id+” option”);

    selectOptions.sort(function(a, b) {
    if (a.text > b.text) {
    return 1;
    }
    else if (a.text < b.text) {
    return -1;
    }
    else {
    return 0
    }
    });

    $("#"+select_id).empty().append(selectOptions);
    }

    Many thanks

    • admin September 1, 2011 4:01 pm

      No problem. Sorry the code doesn’t look very good. You’re the first person to comment code on the blog. I’ll see if I can make it tidier.

  2. Pgonzalez June 10, 2012 2:51 am

    wave / Be careful jQuery(“#selectbox1 :selected”).text() and jQuery(“#selectbox1:selected”).text() are two dienfreft things i wasted lots of time in writing down wrong syntex.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.