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.
[code]
//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);
}
[/code]
Enjoy!
Have a query? Fill out the form below and we’ll get back to you as soon as possible.