Why does the alert coming from my loop always return the last value, not each iteration value?

arrays, javascript, jquery, variables

Solution

By the time you click on the button `i === 3`. Need to pass the value of `i` into a closure:

for (var i = 0; i<theButtons.length; i++) { // do `var i` so the i is not global
    (function(index){
        $(theButtons[i]).on('click', function () {
           alert(index); // index === the value that was passed
        });
    })(i); // pass the value of i
}

Fiddle Demo: http://jsfiddle.net/maniator/fE55Y/3/

Problem

I have a some buttons, which are stored in an array. I then loop through that array to add a click event to each button. Each click alerts the value of `i`. I expect the values to be `1`, `2`, `3` and so on, but they always come back as one value, in case `3`. Can you explain why this happens and how to fix it? Please see this a jsFiddle. Code below: ``` var theButtons = ['.button.one', '.button.two', '.button.three']; for (i=0; i<theButtons.length; i++) { $(theButtons[i]).click(function () { alert(i); // always returns 3 }); } ``` Please explain it as simply and clearly as you can - I'm somewhat of a beginner at Javascript and programming.

Original source

Related problems