0

Hello everyone and thank you for taking the time answering this question.

On my website I have been trying to create three buttons which i have done in html.

ON JS I made an array or items and I tried using DOM so whenever somsone is clicking a button the corresponding item in teh array appears,but as it is right now the alert I am getting is undefined..Can anyone please assist me and help me debug the error?

HTML has :

<button id ="btn-0">Button 1!</button>
<button id ="btn-1">Button 2!</button>
<button id ="btn-2">Button 3!</button>

And JS has :

var items = ['Sugar','Tea','Peper']
for (var btnNum=0; btnNum <items.length;btnNum++){
document.getElementbyId('btn-' + btnNum).onclick = function() {
alert(items[btnNum]);
};
}

Can someone please tell me where I have done a mistake on the JS code and on my alert I am receiving undefined rather than getting hte items of the array?

Apologies for the very novice JS question!

Karui
  • 3
  • 1

1 Answers1

1
var items = ['Sugar','Tea','Peper']
for (var btnNum=0; btnNum <items.length;btnNum++){
  (function(btnNum){
    document.getElementById('btn-' + btnNum).onclick = function() {
  alert(items[btnNum]);
  };
  })(btnNum)

}
Raj
  • 321
  • 1
  • 4