How to call javascript function in html button
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations. Show 1: There's defining it in the HTML:
2: There's adding it to the DOM property for the event in Javascript:
3: And there's attaching a function to the event handler using Javascript:
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification. The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too. Most likely, the problem lies somewhere in your
Try the following instead:
EDIT ExampleExecute a JavaScript when a button is clicked:
Try it Yourself » Definition and UsageThe In JavaScript, using the addEventListener() method: object.addEventListener("click", myScript); Try it Yourself » Technical Details
|