Skip to content

JavaScript onsubmit | Event

  • by

JavaScript onsubmit Event executed when you to submit a HTML form. The JavaScript onsubmit event handling function used for performing the operations in web based applications.

In HTML:

<element onsubmit="myScript">

In JavaScript:

object.onsubmit = function(){myScript};

Using the addEventListener() method:

object.addEventListener("submit", myScript);

JavaScript onsubmit

Simple example code execute a JavaScript when a form is submitted.

<!DOCTYPE html>
<html>
<body>

  <form action="/action_page.php" onsubmit="call()">
    Enter name: <input type="text" name="fname">
    <input type="submit" value="Submit">
  </form>

  <script>
    function call() {
      alert("The form was submitted");
    }
  </script>

</body>
</html>

Output:

JavaScript onsubmit

Another example using validate() function before submitting a form data to the web server. If validate() function returns true, the form will be submitted, otherwise, it’ll not submit the data.

<html>
   <head>
      <script>
         <!--
            function validation() {
               all validation goes here
               .........
               return either true or false
            }
         //-->
      </script>
   </head>
   <body>
      <form method = "POST" action = "t.cgi" onsubmit = "return validate()">
         .......
         <input type = "submit" value = "Submit" />
      </form>
   </body>
</html>

What is the meaning of onsubmit=”return false”?

Answer: This is basically done to handle the form submission via JavaScript. For examplefor validation purposes

See the below code and see how it can be beneficial:

<script language="JavaScript">
myFunctionName() {
    if (document.myForm.myText.value == '')
        return false;
        // When it returns false - your form will not submit and will not redirect too
    else
        return true;
     // When it returns true - your form will submit and will redirect
// (actually it's a part of submit) id you have mentioned in action
}
</script>

<form name="myForm" onSubmit="return myFunctionName()">
<input type="text" name="myText">
<input type="submit" value="Click Me">
</form>

Do comment if you have any doubts or suggestions on this Js event topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading