Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Javascript addeventlistener with parameter in for loop

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!