How to Reset or Clear a Form in JavaScript

08/03/2021

Contents

In this article, you will learn how to reset or clear a form in JavaScript.

Resetting a form

In JavaScript, you can reset or clear a form by accessing the form element and using the reset() method. This method clears all input fields in the form and resets their values to their initial values.

const myForm = document.getElementById('my-form');
myForm.reset();

In this example, the getElementById() method is used to get the form element with the ID of my-form. The reset() method is then called on the form element to reset its input fields.

Resetting a form with a button

You can also reset a form using a button element with the type attribute set to reset. Clicking this button will reset the form.

<form id="my-form">
  <input type="text" name="input-1">
  <input type="text" name="input-2">
  <button type="reset">Reset</button>
</form>

In this example, a form element is created with two input fields and a button element with the type attribute set to reset. Clicking the Reset button will reset the form.

Clearing a form

You can also clear the input fields in a form without resetting them to their initial values. To do this, you can loop through all the input fields in the form and set their values to an empty string.

const myForm = document.getElementById('my-form');
const inputFields = myForm.getElementsByTagName('input');

for (let i = 0; i < inputFields.length; i++) {
  inputFields[i].value = '';
}

In this example, the getElementById() method is used to get the form element with the ID of my-form. The getElementsByTagName() method is then used to get all the input fields in the form. A for loop is then used to loop through all the input fields and set their values to an empty string.