With HTML, a reset button can be added in a form with <input /> tag. For that, we need to specify an attribute type with "reset" value as type="reset"
<input type="reset" value="Reset" />
And when the user clicks on the Reset button, the form that it belongs to will reset to its original state.
This can also be done with JavaScript by using reset() method.
In this tutorial, weโll see how to reset an HTML form with JavaScript.
Example
- Assume that we have an E-commerce website containing login and registration form on the same page like Facebook.
- An HTML form for registration with id
registrationFormwhich will be used by a new customer coming to our website.
<form action="https://example.com/registration" method="post" id="registrationForm">
<!-- .... -->
</form>
So in order to reset this form we will use JavaScript reset() method.
const registrationForm = document.getElementById("registrationForm");
registrationForm.reset();
With method chaining
document.getElementById("registrationForm").reset();
This will restore the form to its original state by clearing all the form elements.
โTalk is cheap. Show me the code.โ
~ Linus Torvalds
Happy ๐ coding
Related Articles
Deepen your understanding with these curated continuations.
Convert array to an object in JavaScript
This article explains simplest and quickest way to convert array to an object in JavaScript. Using widely accepted spread operator `...` makes easy to do it.
How to Update an Array Element in JavaScript
Learn the simplest ways to update array elements in JavaScript. This guide explains how to use assignment operators and modern methods to modify array values.
Flatten an Array One Level Deep in Javascript
This article explains to flatten an array one level deep in javascript comparing with lodash _.flatten method.