HTML onreset Event Attribute

If this site has been useful, we’d love your support! Running this site takes time and resources, and every small contribution helps us keep creating valuable content. Consider buying us a coffee to keep things going strong!

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
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 14th October 2023