[javascript] How to clear all inputs, selects and also hidden fields in a form using jQuery?

I would like to clear all inputs, selects and also all hidden fields in a form. Using jQuery is an option if best suited.

What is the easiest way to do this... I mean easy to understand and maintain.

[EDIT]

The solution must not mess with check-boxes (the value must remain, but checked state must be cleared), nor the submit button.

What I am trying to do is a clear button, that clears all the options entered by the user explicitly, plus hidden-fields.

Thanks!

This question is related to javascript jquery

The answer is


$('#formID')[0].reset(); // Reset all form fields

If you want to apply clear value to a specific number of fields, then assign id or class to them and apply empty value to them. like this:

$('.all_fields').val('');

where all_fields is class applied to desired input fields for applying empty values. It will protect other fields to be empty, that you don't want to change.


I had a slightly more specialised case, a search form which had an input which had autocomplete for a person name. The Javascript code set a hidden input which from.reset() does not clear.

However I didn't want to reset all hidden inputs. There I added a class, search-value, to the hidden inputs which where to be cleared.

$('form#search-form').reset();
$('form#search-form input[type=hidden].search-value').val('');

To clear all inputs, including hidden fields, using JQuery:

// Behold the power of JQuery.
$('input').val('');

Selects are harder, because they have a fixed list. Do you want to clear that list, or just the selection.

Could be something like

$('option').attr('selected', false);

for empty all input tags such as input,select,textatea etc. run this code

$('#message').val('').change();

You can put this inside your jquery code or it can stand alone:

window.onload = prep;

function prep(){
document.getElementById('somediv').onclick = function(){
document.getElementById('inputField').value ='';
  }
}