How to call a JavaScript function on click?


To call a function on click of a button in JavaScript, use onclick. Try to run the following code to call a function onclick in JavaScript −

Example

<html>
   <head>
      <script>
         function sayHello() {
            document.write ("Hello there!");
         }
      </script>
   </head>
   <body>
      <p>Click the following button to call the function</p>

      <form>
         <input type = "button" onclick = "sayHello()" value = "Say Hello">
      </form>

      <p>Use different text in write method and then try...</p>
   </body>
</html>

Updated on: 19-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements