+ 3

How to attach onclick method to input of button type?

Where is my mistake? <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <input id="button1" onclick="alert('Hello World!')" value="Click Me!"> <script> var el = document.getElementById("button1"); el.type = "button"; el.value = "Click me!"; el.onclick="alert('Hello World!')"; </script> </body> </html>

12th Apr 2017, 5:08 PM
Doniyor Djalilov
4 ответов
+ 22
el.onclick = function() {alert("spam");};
12th Apr 2017, 6:16 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 3
el.addEventListener("click", function (){ alert('Hello World'); })
12th Apr 2017, 5:11 PM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 3
Thank you very much! Actually both of them work! I like ValentinHacker's one as its logic is closest to my question. And thank you, Luca and Yaroslav, I will keep in mind Yaroslav's method for adding multiple functions.
13th Apr 2017, 8:04 AM
Doniyor Djalilov
+ 2
Yaroslav's method allows you to bind multiple functions to an event.
12th Apr 2017, 8:51 PM
Luca Garrera