1

[First time on stackoverflow.] I am trying to dynamically add html buttons to my page and then give them a javascript function to run when they are clicked, using jQuery's click. I want to have one button for each element in an array, so I used a for loop. My code looks like this (simplified)

for (var i = 0; i < results.length; i++) {
    $("#" + place[i].place_id).click(function(){console.log("Test");})        
    $("#" + place[i].place_id).click();
}

(I inject buttons with the right id's in the same loop.) This code, when run, console logs "Test" the right number of times, but afterwards, only the last button responds "Test" when clicked. (This situation is a little absurd.) So, I think the event handler ends up using only the final value of i to assign the event handler. I think the problem has to do with closures, but I am not sure how to make a closure out of a jQuery Selector (and in general am not familiar with them).

In contrast, as a hack solution, I "manually" wrote code like the below right below and outside the for loop, and it works as expected, in that clicking causes the console log.

$("#" + place[0].place_id).click(function(){console.log("Test"););
$("#" + place[1].place_id).click(function(){console.log("Test");});
etc.

(Of course, this all occurs within a larger context - specifically a Google Maps Places API call's callback.)

First, am I understanding the problem correctly? Second, what would work? Should I take a different approach altogether, like use a .each()?

(I later would want to display a property of place[i] when clicked, which I would think would need another callback My final hack code looks like this:

$("#" + place[0].place_id).click(function(){google.maps.event.trigger(placeMarkers[0], "click"); repeated 20 times
Yheia
  • 11
  • 2
  • it works fine in [this](http://jsfiddle.net/Cerlin/koj2efmg/) – Cerlin Dec 02 '14 at 05:55
  • [Creating closures in loops: A common mistake](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake) – Arun P Johny Dec 02 '14 at 05:56
  • [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Arun P Johny Dec 02 '14 at 05:56

1 Answers1

1

To do this, you can simply create a self executing function inside the for loop, like this:

for (var i = 0; i < results.length; i++) {
    (function(index) {
        $("#" + place[index].place_id).click(function() { 
            //Do something with place[index] here 
        });
    })(i);
}
Big Bad Waffle
  • 307
  • 1
  • 6