I’ve got two dropdowns, as a result of changing the first one it triggers a jquery change() that does a post with the company id from the first dropdown. That then runs a sql query to get a list of people that work for that company and fills the select box with options. This is working fine and I’ve got the sql query set to ORDER BY admin_name. But when jquery starts inserting the options into the dropdown it appears to be sorting by the option value instead (admin_id). What can I do to keep the options ordered by the admin_name (the text of the option). Below is the jQuery code responsible for adding the options:
$.post("listSignedBy.php", { company_id: company_id },
function(data) {
alert(data); <-- this shows that the data is sorted correctly by the admin name.
var select = $('#signed_by');
if(select.prop) {
var options = select.prop('options');
}
else {
var options = select.attr('options');
}
$('option', select).remove();
var obj = jQuery.parseJSON(data);
options[options.length] = new Option('-- Select Signed By --', '');
$.each(obj, function(val, text) {
options[options.length] = new Option(text, val);
});
select.val(selectedOption);
});
Thank you for any assistance and please let me know if you need any further information to help troubleshoot/fix.
As requested, example JSON data:
{"19082":"Aaron Smith","19081":"Becky Doe"}
So in this case what I WANT is:
<option value='19082'>Aaron Smith</option>
<option value='19081'>Becky Doe</option>
But instead of sorting by the text, it’s sorting by the value so I get:
<option value='19081'>Becky Doe</option>
<option value='19082'>Aaron Smith</option>
The object is not sorted.. It is actually getting inserted in the order how it is iterated.
However, in case if the order of returned response is not in the desired order then the best way is it insert the options first and sort the options. See below,
DEMO: http://jsfiddle.net/gGd82/3/
References: Sorting dropdown list using Javascript