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.


<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>

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

    function call() {
      alert("The form was submitted");



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.

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

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
        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

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

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

Your email address will not be published. Required fields are marked *