350
votes

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.

30
@da5id: Something to keep in mind is that my accepted is also emptying hidden elements! You probably don't want this, so just add :hidden to the not() if your form has any hidden inputs.Paolo Bergantino
Thanks Paulo, very good point that I will bear in mind.da5id
To anyone looking for a good answer, be careful. The accepted answer is on the right track but has bugs. The most voted answer as of now did not understand the question. Many other answers also misunderstood and confused reset with blank/clear.user699082
Mystkine's right- Both the question and currently accepted answer conflate clearing with resetting - I think the questioner was really looking for a multi-stage form reset solution, despite the original title- I've updated the title accordingly.Yarin
hep hep, despite the age of this question i've added a new answer that actually resets arbitrary parts of a form... stackoverflow.com/questions/680241/…kritzikratzi

30 Answers

506
votes

updated on March 2012.

So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.

For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.

My original answer was this:

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

Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.

A more correct answer (but not perfect) is:

function resetForm($form) {
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}

// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name

Using the :text, :radio, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input part of the selector, plus the cache of the form element, this should make it the best performing answer here.

This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.

391
votes

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

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

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

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

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

48
votes

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.
$('INPUT:text, INPUT:password, INPUT:file, SELECT, TEXTAREA', '#myFormId').val('');  
// De-select any checkboxes, radios and drop-down menus
$('INPUT:checkbox, INPUT:radio', '#myFormId').removeAttr('checked').removeAttr('selected');
16
votes

jQuery Plugin

I created a jQuery plugin so I can use it easily anywhere I need it:

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 

So now I can use it by calling:

$('#my-form').clear();
14
votes

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.

14
votes

I usually do:

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

or

$('#formId').get(0).reset()
14
votes

document.getElementById('frm').reset()

5
votes

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.

5
votes

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

var validator = $("#myform").validate();
validator.resetForm();
4
votes

I find this works well.

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

basically none of the provided solutions makes me happy. as pointed out by a few people they empty the form instead of resetting it.

however, there are a few javascript properties that help out:

  • defaultValue for text fields
  • defaultChecked for checkboxes and radio buttons
  • defaultSelected for select options

these store the value that a field had when the page was loaded.

writing a jQuery plugin is now trivial: (for the impatient... here's a demo http://jsfiddle.net/kritzikratzi/N8fEF/1/)

plugin-code

(function( $ ){
    $.fn.resetValue = function() {  
        return this.each(function() {
            var $this = $(this); 
            var node = this.nodeName.toLowerCase(); 
            var type = $this.attr( "type" ); 

            if( node == "input" && ( type == "text" || type == "password" ) ){
                this.value = this.defaultValue; 
            }
            else if( node == "input" && ( type == "radio" || type == "checkbox" ) ){
                this.checked = this.defaultChecked; 
            }
            else if( node == "input" && ( type == "button" || type == "submit" || type="reset" ) ){ 
                // we really don't care 
            }
            else if( node == "select" ){
                this.selectedIndex = $this.find( "option" ).filter( function(){
                    return this.defaultSelected == true; 
                } ).index();
            }
            else if( node == "textarea" ){
                this.value = this.defaultValue; 
            }
            // not good... unknown element, guess around
            else if( this.hasOwnProperty( "defaultValue" ) ){
                this.value = this.defaultValue; 
            }
            else{
                // panic! must be some html5 crazyness
            }
        });
    }
} )(jQuery);

usage

// reset a bunch of fields
$( "#input1, #input2, #select1" ).resetValue(); 

// reset a group of radio buttons
$( "input[name=myRadioGroup]" ).resetValue(); 

// reset all fields in a certain container
$( "#someContainer :input" ).resetValue(); 

// reset all fields
$( ":input" ).resetValue(); 

// note that resetting all fields is better with the javascript-builtin command: 
$( "#myForm" ).get(0).reset(); 

some notes ...

  • i have not looked into the new html5 form elements, some might need special treatment but the same idea should work.
  • elements need to be referenced directly. i.e. $( "#container" ).resetValue() won't work. always use $( "#container :input" ) instead.
  • as mentioned above, here is a demo: http://jsfiddle.net/kritzikratzi/N8fEF/1/
4
votes

You might find that this is actually easier solved without jQuery.

In regular JavaScript, this is as simple as:

document.getElementById('frmitem').reset();

I try to always remember that while we use jQuery to enhance and speed up our coding, sometimes it isn't actually faster. In those cases, it's often better to use another method.

4
votes

I made a slight variation of Francis Lewis' nice solution. What his solution doesn't do is set the drop-down selects to blank. (I think when most people want to "clear", they probably want to make all values empty.) This one does it with .find('select').prop("selectedIndex", -1).

$.fn.clear = function()
{
    $(this).find('input')
            .filter(':text, :password, :file').val('')
            .end()
            .filter(':checkbox, :radio')
                .removeAttr('checked')
            .end()
        .end()
    .find('textarea').val('')
        .end()
    .find('select').prop("selectedIndex", -1)
        .find('option:selected').removeAttr('selected')
    ;
    return this;
};
4
votes

Simply use the jQuery Trigger event like so:

$('form').trigger("reset");

This will reset checkboxes, radiobuttons, textboxes, etc... Essentially it turns your form to it's default state. Simply put the #ID, Class, element inside the jQuery selector.

2
votes

I normally add a hidden reset button to the form. when needed just: $('#reset').click();

2
votes

Modification of the most-voted answer for the $(document).ready() situation:

$('button[type="reset"]').click(function(e) {
    $form = $(this.form);
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    e.preventDefault();
});
1
votes

this worked for me , pyrotex answer didn' reset select fields, took his, here' my edit:

// 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,select option', '#myFormId').removeAttr('checked').removeAttr('selected');
//this is for selecting the first entry of the select
$('select option:first', '#myFormId').attr('selected',true);
1
votes

I'm using Paolo Bergantino solution which is great but with few tweaks... Specifically to work with the form name instead an id.

For example:

function jqResetForm(form){
   $(':input','form[name='+form+']')
   .not(':button, :submit, :reset, :hidden')
   .val('')
   .removeAttr('checked')
   .removeAttr('selected');
}

Now when I want to use it a could do

<span class="button" onclick="jqResetForm('formName')">Reset</span>

As you see, this work with any form, and because I'm using a css style to create the button the page will not refresh when clicked. Once again thanks Paolo for your input. The only problem is if I have defaults values in the form.

1
votes

I used the solution below and it worked for me (mixing traditional javascript with jQuery)

$("#myformId").submit(function() {
    comand="window.document."+$(this).attr('name')+".reset()";
    setTimeout("eval(comando)",4000);
})
1
votes

I'm just an intermediate in PHP, and a bit lazy to dive into a new language like JQuery, but isn't the following a simple and elegant solution?

<input name="Submit1" type="submit" value="Get free quote" />
<input name="submitreset" type="submit" value="Reset" />

Can't see a reason why not have two submit buttons, just with different purposes. Then simply:

if ($_POST['submitreset']=="Reset") {
$_source = "--Choose language from--";
$_target = "--Choose language to--"; }

You just redefine your values back to whatever the default is supposed to be.

0
votes

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.

0
votes

All these answers are good but the absolute easiest way of doing it is with a fake reset, that is you use a link and a reset button.

Just add some CSS to hide your real reset button.

input[type=reset] { visibility:hidden; height:0; padding:0;}

And then on your link you add as follows

<a href="javascript:{}" onclick="reset.click()">Reset form</a>

<input type="reset" name="reset" id="reset" /><!--This input button is hidden-->

Hope this helps! A.

0
votes
<script type="text/javascript">
$("#edit_name").val('default value');
$("#edit_url").val('default value');
$("#edit_priority").val('default value');
$("#edit_description").val('default value');
$("#edit_icon_url option:selected").removeAttr("selected");
</script>
0
votes

Here with the refresh for checkboxes and selects:

$('#frm').find('input:text, input:password, input:file, textarea').val('');
$('#frm').find('input:radio, input:checkbox').attr("checked",false).checkboxradio("refresh");
$('#frm').find('select').val('').selectmenu('refresh');
0
votes

I was having the same problem and the post of Paolo helped me out, but I needed to adjust one thing. My form with id advancedindexsearch only contained input fields and gets the values from a session. For some reason the following did not work for me:

$("#advancedindexsearch").find("input:text").val("");

If I put an alert after this, I saw the values where removed correctly but afterwards they where replaced again. I still don't know how or why but the following line did do the trick for me:

$("#advancedindexsearch").find("input:text").attr("value","");
0
votes

Paolo's answer doesn't account for date pickers, add this in:

$form.find('input[type="date"]').val('');
0
votes

I made a little improvement on Paolo Bergantino's original answer

function resetFormInputs(context) {
    jQuery(':input', context)
    .removeAttr('checked')
    .removeAttr('selected')
    .not(':button, :submit, :reset, :hidden')
    .each(function(){
         jQuery(this).val(jQuery(this).prop('defautValue'));
    });
}

In this way, I can pass any context element to the function. I am able to reset the entire form or only a certain set of fields, for example:

resetFormInputs('#form-id'); // entire form
resetFormInputs('.personal-info'); // only the personal info field set

Plus, the default values of the inputs are retained.

0
votes

here is my solution, which also works with the new html5 input-types:

/**
 * removes all value attributes from input/textarea/select-fields the element with the given css-selector
 * @param {string} ele css-selector of the element | #form_5
 */
function clear_form_elements(ele) {
    $(ele).find(':input').each(function() {
        switch (this.type) {
            case 'checkbox':
            case 'radio':
                this.checked = false;
            default:
                $(this).val('');
                break;
        }
    });
}
0
votes

Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:

function resetForm(formId){
        $('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
        $('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
        $('.select2').select2();
    }
-1
votes
$(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);