Resetting a multi-stage form with jQuery

JqueryResetForms

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

Simply do this

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

More information

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.

Solution 3 - Jquery

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');

Solution 4 - Jquery

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();

Solution 5 - Jquery

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.

Solution 6 - Jquery

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

Solution 7 - Jquery

I usually do:

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

or

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

Solution 8 - Jquery

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.

Solution 9 - Jquery

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

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

Solution 10 - Jquery

I find this works well.

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

Solution 11 - Jquery

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.

Solution 12 - Jquery

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/

Solution 13 - Jquery

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;
};

Solution 14 - Jquery

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.

Solution 15 - Jquery

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

Solution 16 - Jquery

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();
});

Solution 17 - Jquery

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);

Solution 18 - Jquery

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.

Solution 19 - Jquery

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);
})

Solution 20 - Jquery

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.

Solution 21 - Jquery

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.

Solution 22 - Jquery

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.

Solution 23 - Jquery

<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>

Solution 24 - Jquery

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');

Solution 25 - Jquery

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","");

Solution 26 - Jquery

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

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

Solution 27 - Jquery

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.

Solution 28 - Jquery

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;
        }
    });
}

Solution 29 - Jquery

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();
    }

Solution 30 - Jquery

$(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionda5idView Question on Stackoverflow
Solution 1 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 2 - JqueryTiti Wangsa bin DamhoreView Answer on Stackoverflow
Solution 3 - JqueryleepowersView Answer on Stackoverflow
Solution 4 - JqueryFrancis LewisView Answer on Stackoverflow
Solution 5 - JqueryCherianView Answer on Stackoverflow
Solution 6 - JqueryJquery supresserView Answer on Stackoverflow
Solution 7 - JqueryRicardo BinView Answer on Stackoverflow
Solution 8 - JqueryalexView Answer on Stackoverflow
Solution 9 - JquerydmitkoView Answer on Stackoverflow
Solution 10 - JqueryDampeS8NView Answer on Stackoverflow
Solution 11 - JqueryKen LeView Answer on Stackoverflow
Solution 12 - JquerykritzikratziView Answer on Stackoverflow
Solution 13 - JqueryLukeView Answer on Stackoverflow
Solution 14 - JqueryJames111View Answer on Stackoverflow
Solution 15 - JqueryAlberto NunesView Answer on Stackoverflow
Solution 16 - JquerySlawaView Answer on Stackoverflow
Solution 17 - JquerykertalView Answer on Stackoverflow
Solution 18 - JqueryraphieView Answer on Stackoverflow
Solution 19 - JqueryMarcelo MartinsView Answer on Stackoverflow
Solution 20 - JqueryKarelView Answer on Stackoverflow
Solution 21 - JqueryDarryl HeinView Answer on Stackoverflow
Solution 22 - JqueryAndré FigueiraView Answer on Stackoverflow
Solution 23 - JquerysanjayView Answer on Stackoverflow
Solution 24 - Jquerycheckmate711View Answer on Stackoverflow
Solution 25 - Jquerygizmo753View Answer on Stackoverflow
Solution 26 - JqueryLowGainView Answer on Stackoverflow
Solution 27 - JqueryAndré SousaView Answer on Stackoverflow
Solution 28 - JquerypubkeyView Answer on Stackoverflow
Solution 29 - JqueryMarcelo AgimóvelView Answer on Stackoverflow
Solution 30 - JquerymmmView Answer on Stackoverflow