Sort listboxes that have been populated with JSON results.

I was working on a CakePhp project recently and had an Ajax response returning data in the incorrect order even though CakePhp was actually sorting the data correctly.  I thought I would post this handy snippet for anyone that is in a similar position.

//Sort listbox after population with JSON result.
function Sort(elementId) {
    // Convert the listbox options to a javascript array and sort (ascending)
    var sortedList = $.makeArray(
        $("#" + elementId + " option")).sort(function(a, b) { return $(a).text() < $(b).text() ? -1 : 1; }
    );

    // Clear the options and add the sorted ones
    $("#" + elementId).empty().html(sortedList);
}

Enjoy!

Leave a Comment

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

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