How to Reset a Form with jQuery
Clearing a form is something that you often need to do on a website, for example if you want to empty the form fields after submitting a form with Ajax.
Resetting a form using JavaScript is pretty straightforward, you can just call:
document.getElementById("#myform").reset();
But calling the reset()
function on a jQuery object will not work. You’ll get an error saying TypeError: $(...).reset is not a function
.
Why is that?
Well, the reset()
function is a regular JavaScript function, not a jQuery function, and therefore won’t work on a jQuery object.
To get it to work, we need to extract the underlying DOM element from the jQuery object, and then we can call the function.
A jQuery object contains one or more DOM elements, and you can access the elements in it with normal array syntax, so this will work:
$("#myform")[0].reset();
Another way is to trigger the reset event by calling
$("#myform").trigger('reset');
Note that these methods will only reset the form fields to their initial values. It will not empty fields that has default values set on them.