views:

16

answers:

1

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.

thanks

+3  A: 

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 :

for (j=1; j <= 7; j++){
    (function(index) {
        $.getJSON('mobile_json.php', {id:index}, function(data) {
            var select = $('#userAccess' + index);              
            var options = select.attr('options');
            $.each(data, function(index, array) {                   
                options[array['Id']] = new Option(array['Name']);
            });  
        });
     })(j)
 }  

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, leaving j with the value of 8.
That's the tricky thing about closures :)

Felix Kling
I read about this exact thing in the Crockford book. :)
Jacob Relkin
thank you very much
Haim Evgi