Clear form fields with jQuery
This snippet allows you to clear all text fields in a form by triggering the click event on a reset button. It finds the nearest form and targets its input and textarea fields to set their values to an empty string:
By clicking the #resetBtn
, every input field and textarea in the target form is wiped clean, ready to accept new user inputs!
Special cases - checkboxes and selects
Forms can feature various elements such as checkboxes and select boxes. As these have different types of user inputs, they're cleared differently:
- Checkboxes can be unchecked using the jQuery
.prop()
method:
- For select boxes, use
.prop('selected', false)
to clear the value:
Native form reset
And if you feel like going native, HTML forms can be reset to their server-loaded values:
This code snippet calls the native HTML reset method, which intuitively takes care of every field type in your form.
Visualising the process
Imagine your form input fields as an artist's canvas 🎨. The user's inputs are different colors and strokes painting a unique picture (perhaps slightly abstract!).
But now, let's bring out the big guns, the .val('') method:
Voila! Our canvas is back to being a fresh start:
Resetting complex, multi-step forms
How about handling the big boys? We are talking multiple-page, complex forms with various field types. Prepare to be enlightened:
Targeting form sections
In multi-step forms, you may only want to reset the current section. You can achieve this with a combination of the closest
and find
methods:
Targeting specific types of fields
Clear only certain types of fields within a large form. Combine your selectors!
Clear vs reset: Know the difference
It is crucial to discern the difference between resetting a form and clearing a form field.
- Resetting a form restores the default values.
- Clearing a field sets it to an empty string, completely erasing the user's entry.
So, for a full form reset, use $('#myForm').trigger('reset')
, for clearing specific input fields, stick with the faithful .val('')
.
Was this article helpful?