How can I get 4 buttons working with for loop? Each button should perform the same action, in this case the simple alert window here is the html code that I should get working: <html> <head> <title>untitled</title> <script type="text/javascript"> window.onload = function HELLO(BUTTON1) { window.document.getElementById("BUTTON1").addEventListener("click", HELLO, false); alert("Hello world"); } </script> </head> <body> <button id="BUTTON1">Hello World</button> <button id="BUTTON2">Hello World</button> <button id="BUTTON3">Hello World</button> <button id="BUTTON4">Hello World</button> </body> </html>
for(variable = 1; variable <= 4; variable++) { window.document.getElementById("BUTTON1").addEventListener("click", HELLO, false); alert("Hello world"); } Code (markup): Don't think I have a typo
Your code adds the event listener to the same button 4 times. I think the OP wanted to add an event listener to each button. The revised code would look like: for(variable = 1; variable <= 4; variable++) { window.document.getElementById[B]("BUTTON" + variable)[/B].addEventListener("click", HELLO, false); alert("Hello world"); } Code (markup):