How to use onsubmit event attribute In Javascript
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.
<!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:
How to Call a JavaScript Function from an onsubmit Event ?
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:
Table of Content
- Using onsubmit event attribute
- Using the addEventListener() method
Contact Us