JavaScript is one of the core programming language used on the websites. JavaScript enables interactive web pages and is an essential part of web applications. Most of the modern websites relies on JavaScript to handle client side application behavior. All the web browsers have a dedicated JavaScript engine to execute it.
In this tutorial you will learn, how to call a JavaScript function on various page events like: On click , on form submission, or other various HTML controls.
Create JavaScript Function
First of all, create a JavaScript function to use further in this tutorial. Add this JavaScript code between
… tag of the web page. You may also create function under separate JavaScript file and include in HTML page.1 2 3 4 5 6 | <script type="text/javascript"> function myFunction() { var dt = new Date(); alert(dt); } </script> |
The above function will print current datetime in a popup. Let’s call this function on click events of various HTML controls. These HTML controls needs to put under
tag of web page.1. Call JavaScript on Hyperlink Click
Add below HREF html code in body section and access on web browser. Now just click link, It will execute JavaScript’s myFunction which will show current date as per used above.
1 | <a href="javascript:void(0);" onclick="myFunction();"> click here </a> |
2. Call JavaScript on Form Submit
Next, create a sample form to call JavaScript function of form submit event. This is useful for validating form input values and then submit.
1 2 3 4 | <form id="myForm" method="post"> Name: <input name="name" id="name" type="text" /><br /> <input type="button" id="form1" onclick="myFunction();" value="Submit" /> </form> |
3. Call JavaScript on Button Click
Now call JavaScript function of button click event. Add the below code between the body tag of html page. This can be help ful to check form value or verify form values.
1 | <button onclick="myFunction();">click here </button> |
4. Call JavaScript on Link with P Tag
Now call JavaScript function link created using html “p” tag.
1 | <p id="demo" onclick="myFunction()">click here </p> |
1 Comment
Bookmarked!, I really like it!