views:

36696

answers:

10

I have a form with a standard reset button coded thusly:

<input type="reset" class="button standard" value="Clear" />

Trouble is, said form is of the multi-stage sort, so if a user fills out a stage & then returns later, the 'remembered' values for the various fields won't reset when the Clear button is clicked.

I'm thinking that attaching a jQuery function to loop over all the fields and clear them 'manually' would do the trick. I'm already using jQuery within the form, but am only just getting up to speed & so am not sure how to go about this, other than individually referencing each field by ID, which doesn't seem very efficient.

TIA for any help.

+57  A: 

This should do the trick if the ID of your form is myform:

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

It is using the :input selector which will match all input, textarea, select and button elements. Since we are passing #myform as the second argument, it will only find inputs inside this form element. Then it filters out all buttons, submits, resets and hidden inputs using not(). Then it is using val() to set the value of the remaining fields to an empty string, and then it uses removeAttr to remove the checked and selected attribute of the fields in case you have any radio/checkbox/select inputs. Tada.

Paolo Bergantino
That :input is handy... now I know I'll use. Thanks Paolo :) +1
alex
Very nice, cheers, but will this clear the values of my buttons too? Can't test until later.
da5id
@da5id, it may as the docs state it will match 'all input, textarea, select and button elements'. My selectors from my .find() in my answer should remedy this :)
alex
It will match buttons, but I don't think it matches submit or reset buttons. If this is important, check my edit out.
Paolo Bergantino
Ah yes, it will match <button> elements but not <input type="radio|reset"> I think ?
alex
'all input' I can only imagine this would match the submit and reset too.... after all, these ARE input elements, right?
alex
After a quick test :input does match buttons, submits and resets. My 2nd code sample should do the trick.
Paolo Bergantino
@paolo, Thanks for the test... :)
alex
Okay, completely rewrote the damn answer. This one works and is doing the same as the clearForm used by the jQuery Form plugin.
Paolo Bergantino
da5id
Glad we could work together for an answer :)
alex
I just thought of one more case! Yikes, this will never end. :) I added :hidden to the `not` as more likely than not you'd want those to stay as is.
Paolo Bergantino
I was going to suggest you did that in the interests of helping future searchers, but you beat me to it. Thanks again mate!
da5id
At this point I think it'd be better to just list the ones you DO want to empty, so instead of :input in the first line you do ":text, :select, :radio, :checkbox"
Paolo Bergantino
+1 very nice answer
John K
@Paolo: No, I didn't, I landed here by a link from a duplicate question. It was after all thus not a duplicate question. Thanks for the laugh of the day; awesome phrase there in your comment :) I'll delete my previous comment.
BalusC
@BalusC: Fair enough, I will delete my angry response in that case. :)
Paolo Bergantino
+2  A: 

Here is something to get you started

$('form') // match your correct form 
.find('input[type!=submit], input[type!=reset]') // don't reset submit or reset
.val(''); // set their value to blank

Of course, if you have checkboxes/radio buttons, you'll need to modify this to include them as well and set .attr({'checked': false});

edit Paolo's answer is more concise. My answer is more wordy because I did not know about the :input selector, nor did I think about simply removing the checked attribute.

alex
+5  A: 

Clearing forms is a bit tricky and not as simple as it looks.

Suggest you use the jQuery form plugin and use its clearForm or resetForm functionality. It takes care of most of the corner cases.

Cherian
$('#form_id').clearForm(); is just what I needed -- thanks! "Clears the form elements. This method emptys all of the text inputs, password inputs and textarea elements, clears the selection in any select elements, and unchecks all radio and checkbox inputs." (resetForm, on the other hand, "Resets the form to its original state by invoking the form element's native DOM method.")
Tyler Rick
A: 

A method I used on a fairly large form (50+ fields) was to just reload the form with AJAX, basically making a call back to the server and just returning the fields with their default values. This made is much easier than trying to grab each field with JS and then setting it to it's default value. It also allowed to me to keep the default values in one place--the server's code. On this site, there were also some different defaults depending on the settings for the account and therefore I didn't have to worry about sending these to JS. The only small issue I had to deal with were some suggest fields that required initialization after the AJAX call, but not a big deal.

Darryl Hein
+3  A: 

Hey, Cherian!

document.getElementById('frm').reset()
if you are a fan of jQuery this could be rewritten to:$('frm')[0].reset()
dmitko
+61  A: 

From http://groups.google.com/group/jquery-dev/msg/2e0b7435a864beea:

$('#myform')[0].reset();

setting .val('') might not emulate "reset" 100% if you have an input like this:

<input name="percent" value="50"/>

Eg calling .val() on an input with a default value of 50 would set it to an empty string, whereas calling reset() would reset it to its initial value of 50.

Titi Wangsa bin Damhore
thanks, this is a great way to clear a form containing: input type="file".
neoneye
+1 Most reliable and best-performing answer here.
Liam
I think 34 people have misunderstood what the question here is. The asker knows about reset, the form will "reset" to the values that his script is remembering and he needs to force them to be blanked out.
Paolo Bergantino
+2  A: 

I usually do:

$('#formDiv form').get(0).reset()

or

$('#formId').get(0).reset()
Ricardo H.Bin
+1  A: 

I find this works well.

$(":input").not(":button, :submit, :reset, :hidden").each( function() {
    this.value = this.defaultValue;     
});
DampeS8N
+4  A: 

Consider using the validation plugin - it's great! And reseting form is simple:

var validator = $("#myform").validate();
validator.resetForm();
dmitko
+2  A: 

There's a big problem with Paolo's accepted answer. Consider:

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

The .val('') line will also clear any value's assigned to checkboxes and radio buttons. So if (like me) you do something like this:

<input type="checkbox" name="list[]" value="one" />
<input type="checkbox" name="list[]" value="two" checked="checked" />
<input type="checkbox" name="list[]" value="three" />

Using the accepted answer will transform your inputs into:

<input type="checkbox" name="list[]" value="" />
<input type="checkbox" name="list[]" value="" />
<input type="checkbox" name="list[]" value="" />

Oops - I was using that value!

Here's a modified version that will keep your checkbox and radio values:

// Use a whitelist of fields to minimize unintended side effects.
$(':text, :password, :file', '#myFormId').val('');  
// De-select any checkboxes, radios and drop-down menus
$(':input', '#myFormId').removeAttr('checked').removeAttr('selected');
pygorex1