JQuery: I cannot set the value in a loop with a dynamic value

As the following code shows, my business update function always updates input with a final value in an array

for (var i = 0; i < results.length; i++) {
var place = results[i];
var input = $("<input/>").change(function(){update_business(place.name)});

...

}

function update_business(value){

$('#business input').val(value);                                
}
+3
source share
3 answers

The problem is that all of these event handler functions will share the exact same place variable; there is only one. Regarding event handlers, it looks like a global variable.

You can write a separate function that will help:

  function makeHandler(place) {
     return function() {
       update_business(place.name);
     };
   }

Then you can call it in a loop:

 var input = $('<input/>').change(makeHandler(place));

, . "place" "makeHandler", "" . , "".

+2

, .

, , whoms .

(function(j) {
    var place = results[j];
    ...
})(i);

i j, j , i .

+1

.val() . .append, .

.

0
source

All Articles