I’ve created script, which sends AJAX-request and refreshes select element with a list of option elements. After it was done, I try to sort options elements using JQuery plugin jQuery.sortElements.js:
/* If region is specified */
if (regionId != '0') {
/* AJAX request to get city list and refresh select state. */
$.getJSON('/json/cities', {region_id: regionId}, function(json) {
$("select.changedBy-" + regionSelectId).each(function() {
var citySelect = $(this);
$.each(json, function(id, name) {
$('<option value="' + id + '">' + name + '</option>').appendTo(citySelect);
});
});
});
/* Sorting */
$("select.changedBy-" + regionSelectId).each(function() {
$(this).find('option').sortElements(function(option1, option2) {
var option1Value = $(option1).attr('value');
var option2Value = $(option2).attr('value');
if (option1Value == '0') return -1;
if (option2Value == '0') return 1;
if (option1Value == regionId) return -1;
if (option2Value == regionId) return 1;
return $(option1).text() > $(option2).text() ? 1 : -1;
});
});
}
};
Unfortunately, sorting works only if I put breakpoint in Firebug at the following line:
$("select.changedBy-" + regionSelectId).each(function() {
In other case (regular mode) it doesn’t sort option elements. Could you please help me to find the cause of this issue?
Thanks,
Boris.
Sounds and looks like a timing issue. You do realize that the
getJSON()call is asynchronous, right? The JavaScript engine will get to$.getJSON(), make the request and then almost immediately get to your sorting code. It will fail to sort since there won’t be any elements to sort, yet, since the request hasn’t completed.I suspect that when you put a breakpoint, that provides enough time for the request to complete and you see things work the way you expect them to.
I would suggest one of the following
getJSON()callback function, right after you append all the new<option>s<option>sHere’s code for the first suggestion (infinitesimally easier – it involved just cutting and pasting your sorting code into the callback function body):