How to Reset a Form Using JavaScript or jQuery

In this tutorial, we will learn how to reset a form using pure JavaScript and jQuery.

 

Using Pure JavaScript

To reset an HTML form with vanilla JavaScript, we can use the built-in reset() method. To demonstrate this, let's create a simple form with a reset button which will remove all input data when clicked.

 

<form action="/request" method="post" id="request">
  <label for="name">Name</label>
  <input type="text" name="name" id="name">

  <label for="message">Message</label>
  <textarea name="message" id="message"></textarea>

  <button>Submit</button>
  <button type="button" id="form_reset">Reset</button>
</form>
document.getElementById("form_reset").addEventListener('click', function() {
  
  this.form.reset();
});

 

In the above example, we are adding a click event listener to the #form_reset button, when it is clicked the reset() method is used on the parent form.

 

Using jQuery

The following function works in the same way as the JavaScript example but using jQuery markup instead.

 

<form action="/request" method="post" id="request">
  <label for="name">Name</label>
  <input type="text" name="name" id="name">

  <label for="message">Message</label>
  <textarea name="message" id="message"></textarea>

  <button>Submit</button>
  <button type="button" id="form_reset">Reset</button>
</form>
$('#form_reset').click(function() {

  let form = $(this).parent('form:first');

  form[0].reset();
});

 

In the above example, we get the parent form of the reset button when it is clicked and store that object in a variable. We can then use the reset() method on the first element in the form object.

 

Conclusion

You now know how to reset a form using jQuery or pure JavaScript. In this case, I think using vanilla JavaScript is the way to go because, ironically, it looks cleaner.

form reset