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)