i have this code to populate the option in my select box(i have 7 select box in this page) with json response from the server(ajax)
for (j=1; j <= 7; j++){
$.getJSON('mobile_json.php', {id:j}, function(data) {
var select = $('#userAccess' + j);
var options = select.attr('options');
$.each(data, function(index, array) {
options[array['Id']] = new Option(array['Name']);
});
});
}
The problem is after the calling to the ajax, the j equal to 8 ,
what i want is when the function deal with the json array, is set it to the right select box like : userAccess1 , userAccess2 … userAccess7,
how can i deal with it?
It is because you are creating closures in a loop. This helped me to understand it better (especially example 5).
One way to solve this is to create an anonymous function and execute it immediately :
This “captures” the current value of
j. If you don’t do this, by the time the closure (the callback function to the Ajax request) is executed, the loop is already finished, leavingjwith the value of8.That’s the tricky thing about closures 🙂