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
Browser Support
The following information will show you the current browser support for the HTML onreset event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.
This event attribute is supported by all modern browsers.
Desktop
Tablets & Mobile
Last updated by CSSPortal on: 14th October 2023
