JavaScript onsubmit Event Example

Updated on     Kisan Patel

If we want to execute a javascript function when the html form is being submitted, we need to use javascript onsubmit event.

<!-- HTML -->
<form action="" method="post" onsubmit="return TestFunction()">

 Password: <input type="password" name="txtPassword" id="txtPassword"/>

 <input type="submit" id="btn" name="btn" value="Submit" />

<!-- Javascript -->
<script type="text/javascript">
function TestFunction() {
   if (document.getElementById("txtPassword").value == "password") {
      alert("Form submitted successfully!");
      return true;
   else {
      alert("Write \"password\" in the password textbox");
      return false;

In the above code, we have a password textbox and a button in the html form. In the Form we have written onsubmit event that executes when the form submitted to the server. On the onsubmit event we are executing TestFunction() function.

In TestFunction() function, we are checking for the textbox value, if it is “password” then we are returning true otherwise false. As in the onsubmit event we have written return TestFunction() so in case this function returns true and the form is submitted to the server otherwise it is not.

See the Pen xGeGmr by Kisan (@pka246) on CodePen.


Leave a Reply