0

With html I made 3 buttons with successive id's:

<button id="0">btn1</button>
<button id="1">btn2</button>
<button id="2">btn3</button>

I declared an array in js:

var items = ["cars", "trucks", "tankers"]

I made a loop that loops through the buttons, adding an on click listener to each of them. This onclick listener passes the iteration value i to the handle() function:

for (var i = 0; i < items.length; i++) {
    document.getElementById(i).onclick = function(){handle(i)};
}

Handle function:

function handle(index){
    console.log(items[index]);
}

When i run this and click the buttons, instead of getting "cars" when I click btn1, "trucks" when I click btn2 etc I get the value "undefined" instead for each button click.

I am very certain it has something to do with the handle() function not accepting i as an index. what do I do to get the result I want? Am i missing something?

Jonas
  • 121,568
  • 97
  • 310
  • 388
  • Use `let` instead of `var` in the `for` loop. – Pointy Apr 27 '23 at 18:23
  • thanks, that actually worked, what type of problem was that? – Belko DIALLO Apr 27 '23 at 18:28
  • `var` variables are scoped to the enclosing functions, so each one of your event handlers shared the same (single) variable `i`. By using `let`, the variable is scoped to the loop body and each handler has its own `i`. (This has long been a trap for new JavaScript programmers because it's weird and not at all obvious.) – Pointy Apr 27 '23 at 18:44

0 Answers0