I'm attempting to simply get the id of a clicked button and use alert to display it. The code below trys to addEventListener
, if not falls back to attachEvent
. To get the ID, Im trying to pass this.id
as a parameter to myFunction
. but this is not working. I've seen plenty of great solutions using Jquery and the likes, but unfortunately I have to use only plain JS for this. How do I get the ID of a clicked button and store it in a variable to be displayed?
function addEvents()
{
var buttonArray=document.getElementsByClassName('mainButton');
for(i=0; i < buttonArray.length; i++)
{
if (document.addEventListener) {
buttonArray[i].addEventListener("click", myFunction(this.id));
} else if (document.attachEvent) {
buttonArray[i].attachEvent("onclick", myFunction(this.id));
}
function myFunction(clickedId) {
alert("Button" + clickedId + "was clicked.");
}
}
}