I have doubt regarding the execution order for a jquery function i created for my project. The function is given below.
$('#s_cust').change(function(event) {
var custId = $("select#s_cust").val();
$.get('ContactAjax', {
custId: custId
}, function(jsonResponse) {
alert("jsonresp: " + jsonResponse);
cconjson = jsonResponse;
var select = $('#s_ccon');
$(select).find('option').remove();
$('<option>').text("Select").appendTo(select);
$.each(jsonResponse, function(key, value) {
$('<option>').val(key).text(value).appendTo(select);
});
});
if (cconjson != null) {
for (var j = 1; j <= i; j++) {
var select1 = $('#s_ccon' + j);
$(select1).find('option').remove();
alert("test");
$('<option>').text("Select").appendTo(select1);
$.each(cconjson, function(key, value) {
alert("key: " + key + " value:" + value);
$('<option>').val(key).text(value).appendTo(select1);
});
}
}
});
"'#s_ccon' + j"
is given because I'm dynamically generating a text box based on the click of a button.
The problem that I have got while using this function is that, after refresh of the form page I change the value in my select list, s_cust, it goes into the ajax call retrieves my data and populate the s_ccon correctly. When I change value of s_cust again it executes the if loop first, then goes back and does the ajax function get, I understood this beacause the first alert that comes after the second change is alert("test")
, then the alert("key: " + key + " value:" + value)
, after this alert("jsonresp: " + jsonResponse)
.
I don't know why this happens, please tell me the mistake I have made here.