1

Why is the alert I get always "You clicked button 5" in this example? How can I get n to stay at the right value inside the event handler?

html:

<div id="container"></div>

js:

var container = document.getElementById("container");

for ( var n = 0; n < 5; n++) {

    var btn = document.createElement("button");
        btn.innerHTML = "Button " + n;

    btn.onclick = function() {
        alert("You clicked button " + n);        
    }

    container.appendChild(btn);

}

I realize in this example I could just use something like this.innerHTML or assign an attribute to the button with n as its value, but i'm not interested in doing it that way.

heres the fiddle: http://jsfiddle.net/WFNL2/1/

Rob Allsopp
  • 3,309
  • 5
  • 34
  • 53

1 Answers1

2

The issue here is that javascript does not create a scope for for loops, only functions.

You can wrap the loop in a function which you immediately call:

for ( var n = 0; n < 5; n++) {
    (function(n){

        var btn = document.createElement("button");
            btn.innerHTML = "Button " + n;

        btn.onclick = function() {
            alert("You clicked button " + n);        
        }

        container.appendChild(btn);
    )(n);
}

You could also associate the id with the element:

for ( var n = 0; n < 5; n++) {

    var btn = document.createElement("button");
        btn.innerHTML = "Button " + n;

    btn.setAttribute('data-id', n);

    btn.onclick = function() {
        alert("You clicked button " + this.getAttribute('data-id'));        
    }

    container.appendChild(btn);
}
Zack Bloom
  • 8,309
  • 2
  • 20
  • 27