Resetting a multi-stage form with jQuery
Asked Answered
L

31

354

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.

Leath answered 25/3, 2009 at 4:40 Comment(5)
@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.Boarder
Thanks Paulo, very good point that I will bear in mind.Leath
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.Bukhara
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.Tijerina
hep hep, despite the age of this question i've added a new answer that actually resets arbitrary parts of a form... #680741Enfranchise
B
507

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.

Boarder answered 25/3, 2009 at 4:46 Comment(26)
That :input is handy... now I know I'll use. Thanks Paolo :) +1Racquelracquet
Very nice, cheers, but will this clear the values of my buttons too? Can't test until later.Leath
@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 :)Racquelracquet
It will match buttons, but I don't think it matches submit or reset buttons. If this is important, check my edit out.Boarder
Ah yes, it will match <button> elements but not <input type="radio|reset"> I think ?Racquelracquet
'all input' I can only imagine this would match the submit and reset too.... after all, these ARE input elements, right?Racquelracquet
After a quick test :input does match buttons, submits and resets. My 2nd code sample should do the trick.Boarder
Okay, completely rewrote the damn answer. This one works and is doing the same as the clearForm used by the jQuery Form plugin.Boarder
Legendary stuff Gents. My esteem for you both is exceeded only by that for jQuery itself. Marking this answer as accepted & +1 for alex. Cheers :)Leath
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.Boarder
I was going to suggest you did that in the interests of helping future searchers, but you beat me to it. Thanks again mate!Leath
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"Boarder
@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.Studdingsail
It appears that Chrome will override the .val("") call for fields with a value attribute unless you call evt.preventDefault() inside of the click handler.Chantel
@Paolo, I think this also has an unintended effect on radio buttons (which to be clear are not ":button"). Not only will it unselect them, it will also set their value to ''. That means you're actually submitting a blank value (regardless of what you pick). I made a jsFiddle demo with jQuery 1.6.3.Hermosillo
Thanks Paolo, this is awesome, I made some changes to fit my software, instead using the id it uses the form name, just in case there someone else as lazy as me ~ lol example $(':input','form[name=formName]') now I pass the form name value through a function variable an use it in all my forms. Awesome!Mandrel
A problem here is that .val('') resets all values to '' even if these values are used in radio buttons and checkboxes. So when i run the above code i lose valuable information from the form, not just what the user has input.Screw
@Screw i have updated my answer, hope it is better nowBoarder
There seem to be one small problem with this solution - the input:email - it returns an error : Error: Syntax error, unrecognized expression: unsupported pseudo: emailTiercel
This solution is totally incorrect. What about default values? A checkbox can be checked by default, an input could have a value attribute, etc. A reset doesn't clear the values, it returns the form to the initial state.Parochial
@GabrielLlamas I was pretty clear this was a generic solution that addressed a general case of clearing fields out manually, which is what the OP asked for and why this is upvoted. Not being a turnkey solution for different scenarios does not make it incorrect.Boarder
I find clearing all the values using .val([]) to be a better option than .val('')Ow
The function should be called emptyForm rather than resetForm.Malemute
This won't work for the new HTML 5 input types like email and tel. Best to combine both answers so that you omit hidden, checkbox, radio, etc on the first pass. Then clear radios and checkboxes on the second pass.Assiniboine
This answer is exactly what I was looking for! Thank you! I also added $form.find(':input[type=number]').val(''); to clear out number input fields after wondering why input:number kept failing. facepalmSavill
Unfortunately there is a bug :( After using .removeAttr('checked').removeAttr('selected'); when using for the same select JQ method .attr('selected') it doesn't work correct. Needed "Option" get attribute "Selected" but it doesn't shows in select window. In select window shown first option, BUT NOT Selected option. Solution for me was using prop('selected', false) AND prop('selected', TRUE);Bullbat
L
397

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.

Lurcher answered 10/6, 2009 at 6:25 Comment(3)
thanks, this is a great way to clear a form containing: input type="file".Apocrypha
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.Boarder
this works better than all the alternatives hereNeuter
E
48

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');
Exarch answered 10/9, 2010 at 3:44 Comment(8)
For some reason this doesn't work for me on select elements. Can you fix this?Holdall
$(':input,:select', '#myFormId').removeAttr('checked').removeAttr('selected'); should workSculpt
this is the correct answer. If you use the accepted answer, the form does clear after you submit. However, if you want to submit the form again, none of your checkbox or radio button data will be captured since your value attributes will be erased.Olinger
I have updated my answer to address all this, yours is mostly correct aside from the fact jQuery strongly discourages using :text, :password, etc. selectors by themselves without specifying the input part, otherwise it evaluates to *:text which goes through every element in the document instead of just <input> tags with input:textBoarder
@paolo-bergantino Your criticism is incorrect. My examples are scoping the elements to inspect using the #myFormId context passed as the second argument to $() - that is $(':input', '#context') - this is identical to $('#context').filter(':input')Exarch
@powers1 That doesn't change anything, it is still looking for *:input elements within #myform.Boarder
@paolo-bergantino The criticism is half right. Some jQuery selectors like :text should be scoped with a tag name to be more performant. The every element in the document bit was what I was responding to.Exarch
The logic seems very similar in your code and Paolo's modified code, but I find yours easier to follow, hence maintain. In a moderate size form, the selector debate can't make much of a performance difference. Thanks for posting.Carbamidine
B
17

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();
Baez answered 22/7, 2011 at 6:7 Comment(1)
This answer is the best IMO. Should it also include .prop("checked", false)? https://mcmap.net/q/40503/-prop-vs-attrOverliberal
P
14

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.

Pentaprism answered 25/3, 2009 at 5:3 Comment(1)
$('#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.")Crazed
E
14

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

Evelynneven answered 28/5, 2009 at 14:11 Comment(3)
if you are a fan of jQuery this could be rewritten to: $('frm')[0].reset()Plaza
@Plaza Just take a look at the posters usernameTorrlow
While this is a good solution for resetting a form, it's not actually the solution to the question that's being asked.Overliberal
Q
14

I usually do:

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

or

$('#formId').get(0).reset()
Queer answered 27/4, 2010 at 20:8 Comment(1)
such and old post... i have literally tried everything in all posts ... and the only thing that works is your first line of code :(Brewhouse
R
5

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.

Racquelracquet answered 25/3, 2009 at 4:48 Comment(0)
P
5

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

var validator = $("#myform").validate();
validator.resetForm();
Plaza answered 6/7, 2010 at 7:29 Comment(0)
W
4

I find this works well.

$(":input").not(":button, :submit, :reset, :hidden").each( function() {
    this.value = this.defaultValue;     
});
Wildon answered 12/6, 2010 at 22:6 Comment(1)
except that it doesn't work for checkboxes, radio buttons and selects.Enfranchise
F
4

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.

Fubsy answered 7/7, 2011 at 21:50 Comment(0)
E
4

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/
Enfranchise answered 14/5, 2012 at 20:29 Comment(0)
O
4

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;
};
Overliberal answered 30/6, 2014 at 17:51 Comment(0)
L
4

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.

Liver answered 20/6, 2015 at 4:47 Comment(0)
S
2

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

Specht answered 10/10, 2011 at 16:27 Comment(2)
why do you answer a post which has been answered, and approved over 2 years ago? And including this, your post is also low qualityBondage
this is much more obscure than just calling form.reset() directly. there is no need for this hack.Enfranchise
C
2

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();
});
Ciliary answered 15/9, 2012 at 0:19 Comment(0)
J
1

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);
Jacobine answered 15/2, 2011 at 22:43 Comment(0)
M
1

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.

Mandrel answered 13/10, 2011 at 16:6 Comment(0)
A
1

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);
})
Ashjian answered 28/10, 2011 at 18:53 Comment(0)
G
1

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.

Gardie answered 29/8, 2012 at 5:22 Comment(0)
N
0

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.

Nikolai answered 25/3, 2009 at 5:12 Comment(0)
P
0

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.

Punctate answered 24/9, 2011 at 17:45 Comment(0)
S
0
<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>
Shirt answered 5/4, 2012 at 5:46 Comment(0)
P
0

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');
Plasma answered 19/12, 2012 at 19:29 Comment(0)
D
0

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","");
Drink answered 8/2, 2013 at 9:36 Comment(0)
A
0

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

$form.find('input[type="date"]').val('');
Abelmosk answered 10/12, 2013 at 5:12 Comment(0)
H
0

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.

Harday answered 16/6, 2014 at 20:28 Comment(0)
M
0

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;
        }
    });
}
Menstrual answered 26/8, 2014 at 21:30 Comment(1)
You should move the break below the checkbox and radio cases. There's no need for it in its current position.Hemiplegia
U
0

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();
    }
Uranian answered 22/10, 2018 at 0:13 Comment(0)
A
0

Slight update to paolo's answer to fit new input types such as "tel" and email, the following code snippet will select those types as well:

function resetForm(form) {
    form.find('input:text, input[type=email], input[type=tel], input:password, input:file, select, textarea').val('');
    form.find('input:radio, input:checkbox')
         .removeAttr('checked').removeAttr('selected');
}
Acrimony answered 7/6, 2022 at 21:26 Comment(0)
M
-1
$(this).closest('form').find('input,textarea,select').not(':image').prop('disabled', true);
Maori answered 24/12, 2013 at 12:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.