0

I have a function that gets the id of a button when it is clicked, and stores this id in a variable. The same variable cannot be accessed outside of this loop, as it either returns blank or 'undefined'. I have initialised this variable outside of the loop, made it a global variable, and still i cannot access the id that is stored. Please help!

Javascript Function

var button = '';
var buttonid = document.getElementsByTagName("button");
for(var j = 0; j < buttonid.length; j++){
buttonid[j].onclick = function(e){
button = this.id;
 //can see variable is alert is here
//alert(button);

};
}
//cannot see variable if alert is here
//alert(button)
Hannah
  • 17
  • 5
  • use `let` instead. – Harish Soni May 15 '18 at 10:15
  • tried let and still doesn't work – Hannah May 15 '18 at 10:44
  • @T.J.Crowder not sure whether it's a duplicate, the closure doesn't use `i`. – Bergi May 15 '18 at 11:30
  • @Hannah Where exactly do you use `button`? Are you sure the button has already been clicked when you access it? Please post a [mcve] – Bergi May 15 '18 at 11:31
  • @Bergi - Wrong dupetarget, thanks. – T.J. Crowder May 15 '18 at 12:01
  • Hannah - `button` will have the value `''` in the commented-out alert at the end of the code because the click hasn't happened yet, so none of your click handlers has been called. Your click handlers will be called if the user clicks one of the buttons. Trigger whatever it is you want to have happen from code inside the handler, rather than code after the loop. – T.J. Crowder May 15 '18 at 12:02

0 Answers0