jQuery/Javascript function to clear all the fields of a form [duplicate]
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset()
method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden"
.
UPDATE
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger()
:
$('#myForm').trigger("reset");
UPDATE
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
To reset form (but not clear the form) just trigger reset
event:
$('#form').trigger("reset");
To clear a form see other answers.
Something similar to $("#formId").reset()
will not clear form items that have had their defaults set to something other than ""
. One way this can happen is a previous form submission: once a form has been submitted reset()
would "reset" form values to those previously submitted which will likely not be ""
.
One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms()
:
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId"))
:
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.
Note that this will not clear placeholder
text.