0

I feel like this question has already been answered, but I couldn't find it, so I'll ask it anyways.


I was playing with Javascript in HTML, and I decided to make a whole bunch of buttons using a loop. I wanted to assign a function to each one based on which it was. Here, I'll show you the script:

for (var i = 0; i < 6; i++) {
    var button = document.createElement("button");
    button.innerHTML = i;
    button.className = "buttonclass";
    button.onclick = function() {alert(i)};
    var buttonDiv = document.getElementById("buttons");
    buttonDiv.appendChild(button);
}

But when I click on any of the buttons, it returns a "6". I know where the problem is; I can't use simply {alert(i)}. But what should I use instead?

2 Answers2

1

If you are restricted to using var for browser support purposes, you can use functions to properly encapsulate some of these values so that the result isn't hoisted and set to the last value of i.

function generateButtons() {
  var i;
  var buttonDiv = document.getElementById("buttons");
  for (var i = 0; i < 6; i++) {
      generateButton(i, buttonDiv);
  }
}

function generateButton(iteration, container) {
      var button = document.createElement("button");
      button.innerHTML = iteration;
      button.className = "buttonclass";
      button.onclick = function() { alert(iteration); }
      container.appendChild(button);
}

generateButtons();
<div id="buttons"></div>

However, if you are able to use more modern containers like let and const, then you can keep the simpler structure and leverage the magic of block scoped containers:

for (let i = 0; i < 6; i++) {
    let button = document.createElement("button");
    button.innerHTML = i;
    button.className = "buttonclass";
    button.onclick = function() {alert(i)};
    let buttonDiv = document.getElementById("buttons");
    buttonDiv.appendChild(button);
}
<div id="buttons"></div>
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
0

The problem is that when you call alert(i), it is after the loop. After the loop, i is 6. You need to save the value of i, so you can call it later.

for (var i = 0; i < 6; i++) {
    var button = document.createElement("button");
    button.innerHTML = i;
    button.className = "buttonclass";
    var buttonDiv = document.getElementById("buttons");
    buttonDiv.appendChild(button);
    let a = i
    button.onclick = function () { alert(a) };
}