Open In App

How to Call a JavaScript Function from an onsubmit Event ?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The onsubmit event attribute in HTML is triggered when a form is submitted. It is also useful for validating form data or performing actions before any submission and ensures better control and validation of user inputs before data is sent.

The below methods can be used to call a JavaScript function from an onsubmit event:

Using onsubmit event attribute

The onsubmit event can be used to call a function by passing the callback function as a value to the onsubmit attribute in HTML. It will call the passed function once the form is submitted.

Syntax:

<HTMLElement onsubmit = "CallbackFn()">
// Element content
</HTMLElement>

Example: The below code will explain how the onsubmit event can be used as an attribute to call a function.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>GFG</title>
</head>

<body style="text-align: center;">
    <h2>
        How to call a JavaScript function 
        <br/>from an onsubmit event?
    </h2>
    <form onsubmit="Geeks()">
        <label for="firstName">
            First Name:
        </label>
        <input id="firstName" type="text" 
            value="" required/>
        <br /><br/>
        <label for="lastName">
            Last Name:
        </label>
        <input id="lastName" type="text" 
            value="" required/>
        <br /><br/>
        <input type="submit" value="Submit" />
    </form>
    <script>
        function Geeks() {
            alert("Form submitted!!");
        } 
    </script>
</body>

</html>

Output:

fosiGIF

Using the addEventListener() method

In this approach, the addEventListener() method is used to attach an event to a HTML element and call a callback function once the form is submitted.

Syntax:

selectedHTMLElement.addEventListener('submit', callbackFn);

Example: The below code will illustrate the use of addEventListener() method to call a function using onsubmit event.

HTML
<!DOCTYPE html>
<html>

<head>
    <title>GFG</title>
</head>

<body style="text-align: center;">
    <h2>
        How to call a JavaScript function
        <br />from an onsubmit event?
    </h2>
    <form id="formID">
        <label for="firstName">
            First Name:
        </label>
        <input id="firstName" type="text" 
            value="" required />
        <br /><br />
        <label for="lastName">
            Last Name:
        </label>
        <input id="lastName" type="text" 
            value="" required />
        <br /><br />
        <input type="submit" value="Submit" />
    </form>
    <script>
        document.getElementById("formID").
            addEventListener("submit", GFGfun);

        function GFGfun() {
            alert("form submitted!!");
        } 
    </script>
</body>

</html>

Output:

fosiGIF



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads