It doesn’t 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 will look at a straightforward 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 give it an ID. For this example, this will look:
<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 can clear your form using pure JavaScript.
Did you find this helpful? Do you have other methods to achieve a form reset? Let’s hear it, share your feedback.