How to use addEventListener() method In Javascript

Here instead of assigning function to onsubmit parameter of form, we attach event listener to the form element to listen for submit event.

Syntax:

document.getElementById( "form" ).addEventListener( 'submit', formValidation );

Example:To demonstrate calling a JavaScript function from an onsubmit event using event listner method in JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>onsubmit Event</title>
    <style>
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            padding-top: 2rem;
        }

        h1 {
            color: #308d46;
        }
    </style>
</head>

<body>

    <form id="form" action="/post" method="post">
        <h1>GFG Form Example</h1>
        Enter name: <input type="text" name="firstName">
        <input type="submit" value="Submit">
    </form>

    <script>
        document
            .getElementById("form")
            .addEventListener('submit', formValidation);

        function formValidation(event) {
            event.preventDefault();
            let name =
                event
                    .target
                    .firstName
                    .value
            if (name.length == 0) {
                alert("Enter Valid Name");
                return false;
            }
            alert("Form Submitted")
        }
    </script>
</body>

</html>

Output:

Using addEventListner method in JavaScript



How to Call a JavaScript Function using an onsubmit Event ?

HTML has a form element that is used to get the data from the user and send the data to the server. Before the HTML form sends data to the server, it generates an event called “submit”.

This event can be utilized to execute a JavaScript function that can either validate the form data or notify the user of the form submission.

Below are the approaches to call a JavaScript function using an onsubmit event:

Table of Content

  • Using Inline event handler in HTML
  • Using on submit attribute in JavaScript
  • Using addEventListener() method in JavaScript

Similar Reads

Using Inline event handler in HTML

Here in the HTML form we pass the javascript function as string to onsubmit parameter of form. when the form submit’s, It will run the function....

Using on submit attribute in JavaScript

Instead of assigning the function directly inside the form parameter, we can select the form element using javascript and assign the function to onsubmit parameter from their....

Using addEventListener() method in JavaScript

Here instead of assigning function to onsubmit parameter of form, we attach event listener to the form element to listen for submit event....