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.
<!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:
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