edit1: after further investigation, if I don't use ajax/getJSON to get the value for my list, it actually works. something like below works. but once I use ajax even if it's only returning 3 countries, I get weird behavior getting the currently selected value.
$("#country").append($('<option></option>').attr("value", "Argentina").text("Argentina"));
$("#country").append($('<option></option>').attr("value", "Australia").text("Australia"));
$("#country").append($('<option></option>').attr("value", "Bangladesh").attr("selected", "selected").text("Bangladesh"));
$("#country").append($('<option></option>').attr("value", "China").text("China"));
edit2: seems this has something to do with settings async = false when making the ajax call. It's working now. (Is it possible to set async:false to $.getJSON call)
I've seen various discussion here and elsewhere on how to go about this but my post is different where I am creating the options in the dropdown list on-the-fly. I do not encounter this problem if I precreate the list.
My problem is that the getCities, getAgencies and the alert functions never gets the correct value. The alert function either displays an empty string (i.e. "") or the null value. But the weird thing is when it reaches the displaySearchResults function it is getting the right value.
getCities, getAgencies and displaySearchResults contains .getJSON function which passes the values I supplied to the functions. I am monitoring/debugging these using firebug.
I've tried
- $(#"country :selected").val()
- $("#country").find(":selected").text()
- $("#country").text()
- same as the 3 above but using .val() instead.
my code:
$(document).ready(function(){
onLoad();
function onLoad() {
getCountries("Australia");
getCities($("#country").find(":selected").val());
getAgencies($("#country").find(":selected").val(), null);
alert($("#country").find(":selected").text());
displaySearchResults($("#country").find(":selected").val(), null, null);
}
function getCountries(country) {
$.getJSON("index.html/agents/getCountries?format=json", {}, function(data, status) {
if (data.length > 0) {
$("#country").empty();
$.each(data, function () {
if (this.COUNTRY != country) {
$("#country").append($('<option></option>').attr("value", this.COUNTRY).text(this.COUNTRY));
} else {
$("#country").append($('<option></option>').attr("value", this.COUNTRY).attr("selected", "selected").text(this.COUNTRY))
}
});
}
});
}
function getCities(country) {
$.getJSON("index.html/agents/getCities?format=json", {country:country}, function(data, status) {
if (data.length > 0) {
$("#city").empty();
$("#city").prepend($('<option></option>').attr("value", "").attr("selected", "selected").text("- Choose a city -"));
$.each(data, function () {
$("#city").append($('<option></option>').attr("value", this.CITY).text(this.CITY));
});
}
});
}