onsubmit

The onsubmit event in HTML is triggered when a <form> is submitted, allowing scripts to validate the data or perform actions before the <form> submission is completed.

onsubmit

The onsubmit event in HTML occurs when a user submits a <form>, allowing developers to run specific actions or scripts before the <form> is submitted to the server. This event is useful for tasks like form validation, data processing, or preventing the default form submission behavior. The onselect event is commonly used with <input type="text"> or <textarea> elements.

Syntax

In HTML

index.html
<element onsubmit="myScript">

In JS

script.js
object.onsubmit = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("submit", myScript);

Example

::event-onsubmit ::
index.html
<!DOCTYPE html>
<html>
<body>
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form action="/action_page.php" onsubmit="myFunction()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

<script>
function myFunction() {
  alert("The form was submitted");
}
</script>

</body>
</html>

Explanation

  1. Form Submission: When the user enters their name and clicks the "Submit" button, the handleSubmit function is called.
  2. Prevent Default Action: The event.preventDefault() method is utilized to prevent the form from submitting in the usual manner, which would cause a page reload.
  3. Alert Notification: An alert pops up, greeting the user with the name they entered in the input field.

This example shows how to manage form submission using JavaScript while preventing the default action.

Values

Conclusion

The onsubmit event provides a powerful way to handle <form> submissions in HTML. By using this event, developers can validate user input, prevent unwanted form submissions, and perform necessary actions before the form data is sent to the server.