0

I am trying to add onclick listeners to a list of buttons, the id of the buttons is in a range of 0-array length in this pattern btn1-btn2-btn3 and so on

I use a for loop to get the buttons by id and the event listeners against the fetched dom element:

for(var i =0; i<length; i++){
  console.log("log 1: Adding listener for "+i);
  document.getElementById("btn"+i).addEventListener("click", function(){
  myFunc(i);
  });
}

The Function

myFunc(i){
  alert(i);
}

The Problem

No matter what button I click, I always get the last number in the for loop in the alert. I have checked and all buttons have different id's and the log 1 output is correct( ten logs 0-9). However log 2 output is the last number 10 no matter what button I click.

I want to know how I can pass the iterator(i) in the onclick listener. Any advice or suggestion will be agreat help to this newbie,Thanks!

Shahzaib
  • 103
  • 1
  • 11
  • 1
    A small suggestion, this is pretty simple code- adding a working example makes it much easier for people to reply! – Jeff B Mar 07 '22 at 17:53
  • 2
    Try using `let` instead of `var` in your for loop. https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript/500459#500459 – James Mar 07 '22 at 17:55

0 Answers0