Reset All Form Fields With Simple Javascript

How to add a form button to reset all form fields using pure Javascript.

Reset All Form Fields With Simple Javascript

It doesn’t really matter why you might want to add a reset form button for your users. It could be that the form has conditional logic, is super long, complex, or that it has form fields that are prone to user error. We are going to look at an incredibly simple way to add a form button to reset all form fields using simple and pure Javascript.


Let’s Break Down The HTML Form Code

The biggest starting factor with your HTML form code at this stage is to simply give it an ID, for this example this will look like:

<form id="myform" action="#">

Now We Want to Bring In The Form Markup

This form reset function will clear all form fields so the rest of your form markup can really look however you choose pertaining to classes and IDs. For this example our complete form with the added reset button will look like:

<form id="myform" action="#">
  <input type="text" name="name" placeholder="Your Name" />
  <input type="text" name="email" placeholder="Your Email" />
  <input type="checkbox" name="option">
  <input type="button" onclick="newFunction()" value="Reset Form" />
  <input type="submit"  value="Submit Form" />
</form>

Reset All Form Fields With Javascript

Now we want to bring in our last piece of code which is our pure Javascript, this code should be placed directly under the </form> tag. This simple Javascript code snippet contains the magic necessary to recognize your form ID and uses the onclick action to clear the form when the reset button is clicked. The complete code looks like:

<form id="myform" action="#">
  <input type="text" name="name" placeholder="Your Name" />
  <input type="text" name="email" placeholder="Your Email" />
  <input type="checkbox" name="option">
  <input type="button" onclick="newFunction()" value="Reset Form" />
  <input type="submit"  value="Submit Form" />
</form>
<script>
function newFunction() {
document.getElementById("myform").reset();
}
</script> 

There you have it folks, now you have the ability to clear your form using pure Javascript. Happy coding! Did you find this helpful? Do you have other methods to achieve a form reset? Let’s hear it, share your feedback in the comments.

Back to Blog

Leave a Reply

Your email address will not be published. Required fields are marked *