GET IN TOUCH WITH US: +353 (0)61 514582

Sort listboxes that have been populated with JSON results.

June 2nd, 2013 Synnott Lawline Logo

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);


Next Post: How to deal with Ajax Caching in IE Previous Post: Adding an upload filetype to WordPress
Get In Touch

Have a query? Fill out the form below and we’ll get back to you as soon as possible.