HTML onreset Event Attribute
Description
The HTML onreset
event attribute specifies a JavaScript function to be run when a form is reset. The onreset
event can be used to perform tasks such as:
- Clearing the values of all form fields
- Validating the form data
- Displaying a confirmation message before the form is reset
The onreset
event attribute can be used on the <form>
element. The value of the onreset
attribute is the name of the JavaScript function to be run when the form is reset.
For example, the following HTML code specifies a JavaScript function called resetForm()
to be run when the form is reset:
<form onreset="resetForm()">
<input type="text" name="name">
<input type="submit">
</form>
The resetForm()
function could be used to clear the values of all form fields:
function resetForm() {
// Clear the values of all form fields
var form = document.querySelector('form');
for (var i = 0; i < form.elements.length; i++) {
form.elements[i].value = '';
}
}
The onreset
event can also be used to validate the form data before the form is reset. For example, the following JavaScript function validates the form data and displays a confirmation message before the form is reset:
function resetForm() {
// Validate the form data
var name = document.querySelector('input[name="name"]').value;
if (name === '') {
alert('Please enter your name.');
return false;
}
// Display a confirmation message
var confirm = window.confirm('Are you sure you want to reset the form?');
if (!confirm) {
return false;
}
// Clear the values of all form fields
var form = document.querySelector('form');
for (var i = 0; i < form.elements.length; i++) {
form.elements[i].value = '';
}
}
Syntax
<element onreset="script">
Values
- scriptThe name of the script to use when the event has been triggered.
Example
<!DOCTYPE html>
<html>
<head>
<title>onreset event</title>
</head>
<body>
<form onreset="testFunction()">
Enter something and discard:<br>
<input type="text" name="info"><br>
<input type="reset">
</form>
<script>
function testFunction() {
alert ("EXAMPLE: The form has been reset!");
}
</script>
</body>
</html>
Browser Support
The following table will show you the current browser support for the HTML onreset
Event Attribute.
Desktop | |||||
Yes | Yes | Yes | Yes | Yes |
Tablets / Mobile | |||||
Yes | Yes | Yes | Yes | Yes | Yes |
Last updated by CSSPortal on: 14th October 2023