[jquery] Resetting a multi-stage form with jQuery

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.

This question is related to jquery reset forms

The answer is


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

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

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

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


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

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.


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

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

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

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

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

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

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.


I usually do:

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

or

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

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.


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

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.


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

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

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.


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.


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.


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

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.


I find this works well.

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

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.


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/

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

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

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


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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to reset

How to reset a form using jQuery with .reset() method Reset all the items in a form How to reset db in Django? I get a command 'reset' not found error How to git reset --hard a subdirectory? How do I revert back to an OpenWrt router configuration? Wipe data/Factory reset through ADB Fastest way to reset every value of std::vector<int> to 0 How do I reset the setInterval timer? How to reset par(mfrow) in R Reset auto increment counter in postgres

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"