onsubmit
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
<element onsubmit="myScript">
In JS
object.onsubmit = function(){myScript};
addEventListener()
function is used. In JavaScript, the
object.addEventListener("submit", myScript);
Example
<!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
- Form Submission: When the user enters their name and clicks the
"Submit"
button, thehandleSubmit
function is called. - 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. - 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.
onselect
The onselect event in HTML is triggered when a user selects text within an <input> or <textarea> element, enabling scripts to respond to this interaction.
Keyboard
HTML keyboard event attributes manage user interactions involving key presses and releases, enabling dynamic responses to keyboard input.