javascript
  1. javascript-reset

JavaScript Reset

JavaScript reset is a concept in which we reset the values of all the form elements on a webpage with the help of JavaScript. This is used when we want to clear the form values on submission or any other user action. In this article, we will discuss the syntax, example, output, explanations, use cases, important points, and the summary of JavaScript reset.

Syntax

document.getElementById("formId").reset();

Here, the formId will be the id of the form whose values we want to reset.

Example

<form id="myForm">
  <input type="text" name="name" value="John">
  <input type="text" name="email" value="john@example.com">
  <button type="button" onclick="resetForm()">Reset Form</button>
</form>

<script>
function resetForm() {
  document.getElementById("myForm").reset();
}
</script>

Explanation

In the above example, we have a form with two input fields and a button. The onclick event of the button is attached with a JavaScript function resetForm(). The function uses the reset() method of the form element to reset the form values.

Use

The JavaScript reset can be used in various scenarios such as:

  • Clearing form values on submission
  • Clearing form values on a user action
  • Resetting form values after an unsuccessful submission or validation error

Important Points

  • The reset() method will reset the values of all the form elements in the specified form.
  • The form must have a unique id attribute to use this method.
  • The reset() method will reset all the values to their initial default values, as specified in the HTML code.

Summary

JavaScript reset is a great feature for clearing the form values. By using the reset() method of the form element, we can reset all the form values to their initial default values. This is useful in situations where we want to clear the form data on user actions or submission.

Published on: