View video tutorial

HTML onsubmit Attribute

HTML

The HTML onsubmit attribute is an event handler used to specify a script that will run when a <form> is submitted.

Definition and Usage


➔ This event is useful when client-side form validation, displaying confirmation messages, or preventing invalid form submission behavior is required.

➔ If the verification is successful, the data is sent to the server, if the verification fails, the submission is stopped. <form onsubmit="return validateData()"> here the validateData() function returns true or false.

➔ This event works with <input type="submit"> or <button type="submit">

➔ The action attribute specifies the URL where the form data will be sent (usually a server-side script) and the onsubmit script runs before the form is submitted to the action URL.

Syntax
//In HTML
<form onsubmit="myFunction()" id="sample">
  <!-- form input elements goes here -->
</form>


//In javascript
document.getElementById("sample").onsubmit=function() {myFunction();};
//OR
document.getElementById("sample").addEventListener("submit", myFunction);
//OR 
document.getElementById("sample").addEventListener("submit", (event) => {
    myFunction();
 });

Applies to

This attribute can be used on the following element.

Attribute Element
onsubmit <form>