Alex Marple Alex Marple - 2 months ago 8
Javascript Question

JavaScript buttons returning wrong alert

I'm applying for a job and they threw a JS question detailed below:

Write a function to render 10 elements on the page, numbered 1 through 10, and alert the number of the chosen button when one is clicked. Do not use jQuery or any other libraries.

Seems easy enough. I've built a working model except for it alerts the wrong number. It alerts Button 11 for all the buttons. I know I'm forgetting something simple. Below is my code (feel free to critique it if you have a better way of organizing this). Also here is a link to a JSFiddle that works save for the alert.

var count = 1;

function createBtn(){
var button = document.createElement("button");
button.innerHTML = "Button " + count;
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
button.addEventListener ("click", function() {
alert('Button ' + count);
});
}

function buttonRender(){
for(var i = 0; i < 10; i++){
createBtn();
count++;
}
}

buttonRender();

Answer

You should pass count to the function.

function createBtn(count){
  var button = document.createElement("button");
  button.innerHTML = "Button " + count;
  var body = document.getElementsByTagName("body")[0];
  body.appendChild(button);
  button.addEventListener ("click", function() {
    alert('Button ' + count);
  });
}

function buttonRender(){
  for(var i = 0; i < 10; i++){
    createBtn(count);
    count++;
  }
}

https://jsfiddle.net/xw7mhag2/