Clearing Form Data

read 46 comments

A question I often hear is, "How do I clear a form?"

Initially the answer seems very straightforward - a one-liner in jQuery:

$('form :input').val("");

But upon closer examination we find that this is a bad way to solve the problem. When someone says they want to "clear a form" what they really mean is that they want to clear the visible state from all the form fields. With this in mind, the code above is clearly not the right way to get the job done. First, it will blast away the values of hidden inputs, checkboxes and radio buttons. Not good. The values of those fields should not be altered. And second, it does not properly account for select elements. What we need is something smarter. Here's a start:

JavaScript:
  1. function clearForm(form) {
  2.   // iterate over all of the inputs for the form
  3.   // element that was passed in
  4.   $(':input', form).each(function() {
  5.     var type = this.type;
  6.     var tag = this.tagName.toLowerCase(); // normalize case
  7.     // it's ok to reset the value attr of text inputs,
  8.     // password inputs, and textareas
  9.     if (type == 'text' || type == 'password' || tag == 'textarea')
  10.       this.value = "";
  11.     // checkboxes and radios need to have their checked state cleared
  12.     // but should *not* have their 'value' changed
  13.     else if (type == 'checkbox' || type == 'radio')
  14.       this.checked = false;
  15.     // select elements need to have their 'selectedIndex' property set to -1
  16.     // (this works for both single and multiple select elements)
  17.     else if (tag == 'select')
  18.       this.selectedIndex = -1;
  19.   });
  20. };

We can improve upon this function by making it a plugin which can be called on a form element:

JavaScript:
  1. $.fn.clearForm = function() {
  2.   // iterate each matching form
  3.   return this.each(function() {
  4.     // iterate the elements within the form
  5.     $(':input', this).each(function() {
  6.       var type = this.type, tag = this.tagName.toLowerCase();
  7.       if (type == 'text' || type == 'password' || tag == 'textarea')
  8.         this.value = '';
  9.       else if (type == 'checkbox' || type == 'radio')
  10.         this.checked = false;
  11.       else if (tag == 'select')
  12.         this.selectedIndex = -1;
  13.     });
  14.   });
  15. };

One last improvement we can make is to allow for the method to be called on forms, form elements, or both:

JavaScript:
  1. $.fn.clearForm = function() {
  2.   return this.each(function() {
  3.     var type = this.type, tag = this.tagName.toLowerCase();
  4.     if (tag == 'form')
  5.       return $(':input',this).clearForm();
  6.     if (type == 'text' || type == 'password' || tag == 'textarea')
  7.       this.value = '';
  8.     else if (type == 'checkbox' || type == 'radio')
  9.       this.checked = false;
  10.     else if (tag == 'select')
  11.       this.selectedIndex = -1;
  12.   });
  13. };

Voila! Now we have a plugin for clearing form fields that can be called like this:

JavaScript:
  1. $('form').clearForm()

Or like this:

JavaScript:
  1. $(':input').clearForm()

You can find this same functionality implemented in the jQuery Form Plugin.

comment feed

46 comments

  1. Estevão Lucas

    There are also the method reset, where we can go back for initial state


    $( "form" )[ 0 ].reset();

  2. I definitely think that $('form')[0].reset() is more desirable, as it will respect form defaults and the browser’s native behaviour, as well as avoiding the overhead of looping through all the elements with jQuery selectors.

    If anything I’d like to see a $('form').reset() which used the browser’s native behaviour and returned the jQuery object to continue the chain. Perhaps this is one for the core though.

  3. Estevão and Dave - thanks for bringing up the "reset" method. Reset, of course, is a different action than clearing the form (although they could be the same depending on the form's initial state). I was trying to provide a fool-proof way of clearing form data, regardless of initial state, but I should have mentioned the reset method too! What's nice about the plugin that I presented is that you can call it on a subset of the form (or any input container for that matter). So if you needed to clear only the fields within a "warning" div you could do this:

    $('div.warning').clearForm();

  4. It seems easiest to use a HTML input element of the type reset, to achieve this functionality.

  5. yaph, please read comment #3 above. Mike does a very good job of explaining the difference between what <input type="reset"> does and what his plugin does.

  6. For special cases, where you only want to reset certain parts of the form this plug-in is useful, but for cases where you want to reset all fields to the initial state a reset button seems the best choice, because it works without JavaScript.

  7. Cadaeib

    Hi,
    In some case with Firefox the "reset" method don't reset the form (why ? i don't know ...), so this solution is good in this special case ... Perhaps better if you reset also the 'hidden' fields ;o)
    Many thxs for this script.

  8. Sascha

    You should mind <select> and <textarea> also, shouldn´t you? :)

    Sascha

  9. @Sascha: The code handles select and textarea elements. Give it a try!

    @Cadaeib: I do not advise resetting input elements of type hidden. The values of those elements are usually not meant to ever change so a generic function like the one provided here should leave them alone.

  10. Great stuff- perfect intro into basic forms with JQuery - thanks very much.

  11. Robsworld

    Hi guys I noticed that when using: $( "form" )[ 0 ].reset(); that trying to read a value in IE fails.

    i.e.

    test1

    if I do $( "form" )[ 0 ].reset(); then call $('#days').val() it returns an empty string

    I thought reset should return back to initial state not clear the forms to nothing?

    Does the option have to have selected in it???

    Regards Robsworld

  12. For some reason, line 7 wasn't working for me (FF2, linux). I had to change it to:

    this.setAttribute('value','');

  13. Ockham razor ...

    $('#ClearFormButton').click(function() {
        if(confirm("Clear form?")) {
            $("#id_Of_Display_None_Type_Reset_Input").click();
           &nbsp$(".other_Form_Elements_Not_Cleared_By_Reset_Such_As_Hidden_Inputs").remove();
        }
        return false;
    });

  14. Martin McWhorter

    I am all about jQuery -- but for reseting a form the safest method is to give your form a name:

    <form name="myform">....</form&gt
    

    Then use

    document.forms['myform'].reset()

    to reset the form.

  15. Handrus Nogueira

    The form reset is pretty good sometime, but as said above, it will brings the form to initial state, on dinamic pages sometimes the form start with values...
    Great function!

  16. Chad

    RE: Martin. I am all about jQuery.

    FYI: $("form")[0].reset() will be translated to:
    document.forms[0].reset()

  17. I am also all about JQuery, but I assume converting DOM objects to JQuery objects unnecessarily is going to add to memory overhead, and my not be the most efficient way of doing things.

    If you just want to reset all the forms on your page, this should work:

    var formLen = document.forms.length;
    for( var i = 0; i < formLen; i++ ){
    document.forms[i].reset();
    }

  18. Eduardo Padoan

    Thanks for this! I have a use case for this plugin: a form that "remembers" the last selected options. There was only a little problem: all selectedIndex where set to -1, so all my select tags where blank when you used ir. The 'empty' value for my selects is 'All' or '----------' (index 0), except selects with multiple='multiple', so I have made this change:

                    this.checked = false;
    +        else if (tag == 'select' && this.multiple)
    +            this.selectedIndex = -1;
                else if (tag == 'select')
    -               this.selectedIndex = -1;
    +               this.selectedIndex = 0;
         });
    
  19. Patrick

    As was mentioned several times above but nobody seems to be getting, resetting a form and clearing a form are two completely different things. If you want to reset a form, then by all means use a reset button or something. If you want to clear a form's fields then reset buttons won't do jack if your form was created with text in the fields already.

    I've never actually needed a reset button, I've always needed clear, so this is perfect for me.
    Thanks for the example!

  20. Alternatively, the whole thing can be done via a switch statement ala:

    $.fn.clearForm = function() {
      return this.each(function() {
        if (this.tagName.toLowerCase() == "form") {
          return $(":input",this).clearForm();
        }
        switch (this.type) {
          case "password":
          case "textarea":
          case "text":
            this.value = "";
            break;
          case "select-multiple":
          case "select-one":
            this.selectedIndex = -1;
            break;
          case "radio":
          case "checkbox":
            this.checked = false;
            break;
        }
      });
    };
  21. Aaron

    I feel like a d-bag for having to ask this, but I'm just getting started with jquery. Where is the best place to include: $('form').clearForm(), and in what form? I'm still a little cloudy on how to connect the HTML and JS.

  22. I tried all above variations but I got no success. So I wrote this code and it worked to me:

    
    $.fn.clearForm = function() {
        this.each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (tag == 'form')
                return $(':input',this).clearForm();
            if (type == 'text' || type == 'password' || tag == 'textarea')
                this.setAttribute('value', '');
            else if (type == 'checkbox' || type == 'radio')
                this.removeAttribute('checked');
            else if (type == 'select-one' || tag == 'select')
                $('option', this).each(function(){
                    this.removeAttribute('selected');
                });
        });
    };
    
  23. kaineer

    This one works fine for me (firefox 3.0, jQuery 1.2.6)

    $.fn.clearForm = function() {
      $( this ).
        find( ':text, :password, textarea' ).
          attr( 'value', '' ).end().
        find( ':checkbox, :radio' ).
          attr( 'checked', false ).end().
        find( 'select' ).
          attr( 'selectedIndex', -1 );
    }
  24. The plugin was very useful to me. If you use the jquery validation plugin you should definitely do this to reset the default warnings too:
    $("label,:input,textarea",this).removeClass("error");
    If you use custom messages you should adapt the line above.

  25. Dallas

    Thanks.. new to Jquery-- nice intro and eye openner.

  26. I'm having the same problem as comment #11. After a reset ( input type="reset" ) if I then try to read the values from the select fields in IE I get nothing. Anybody else see this problem?

  27. Simply Seth

    how do I reset the radio buttons to the default (which is 'GB' )??

    
    KB <input type="radio" name="curr_unit" value="KB" />
    MB <input type="radio" name="curr_unit" value="MB" />
    GB <input type="radio" name="curr_unit" value="GB" checked/>
    TB <input type="radio" name="curr_unit" value="TB" />
     
  28. Just a note: if you change the last line

    else if (tag == 'select') this.selectedIndex = -1; });
    to
    else if (tag == 'select') this.selectedIndex = 0; });

    it will reset your select boxes back to the "--- select one ---" heading that most of us use

    SUMMARY: SET the selected.Index value to Zero (0)

  29. 4g63

    another way to reset form with jquery - $('my-form').get(0).reset();

  30. i like this post, thank you for your post, best work !

    xman

  31. Mushimas

    A little cleaner?

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

    assuming your form has 'myform' id

    • Curt Grymala

      @Mushimas - Unfortunately, the code you provided will also blank out the "value" attribute for radio buttons and checkboxes, making them completely useless.

      I'm currently testing a slightly modified version of your code to see if it works or not. It looks something like:

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

      Still some testing left to do, but it's looking like the code I provided above should work. Thanks for the inspiration.

      Mike - Thanks for the tips. It's tough to find good resources for actually clearing a form rather than resetting it. This has been really helpful.

  32. johans

    Why not just make a clone of the initial form and replace the form with that to reset?

    // store initial form
    var $originalForm = $('form').clone();

    // to reset form replace with clone and keep a clone for next reset
    $('form').replaceWith($originalForm.clone());

    This also retains all default values - button enable/disable states, radio/checkbox selected states, and select lists etc.

  33. Madan

    I feel that this coding is much more sensible

    $('#sampleform').get(0).reset();

  34. bill

    Like the few who seem to "get" this thread, I needed a clear, not just a reset, and you have made my day. 1,000,000 thank yous.

  35. ouardisoft

    this function is compatible with HTML5 inputs (url, email, ...)

    
    $.fn.clearForm = function() {
      return this.each(function() {
     var type = this.type, tag = this.tagName.toLowerCase();
     if (tag == "form")
       return $(":input",this).clearForm();
         if (type == "text" || type == "password" || tag == "textarea")
           this.value = "";
         else if (type == "checkbox" || type == "radio")
           this.checked = false;
           else if (type == "hidden"){}
         else if (tag == "select")
           this.selectedIndex = -1;
           else
           this.value = "";
      });
    };
    
    

    Call

    $("form").clearForm();

  36. Krzysztof Alboszta

    Hi,
    the plugin functionality would be more useful when you remeber about <fieldset> tag:
    ...
    if (tag == 'form' || tag == 'fieldset')
    return $(':input',this).clearForm();
    ...

    this is the best reason to use clear instead of reset method.. when you have to clear the values of big one part of the form

  37. Very cool piece of work. I was able to clean up the form data on jquery dialog close to prevent cached field data being shown. Nice Work.

  38. Jean-Luc Tallis

    Here are 3 possible suggestions, including 2 that have already been mentioned.
    $("form").clearForm(); // with the plugin
    $("form")[0].reset();
    $('form > input[type=reset]').trigger('click'); //with a reset button in the form set to display: none;
    Of course, depending on the result you want (total clear, or reset to defaults) will be which one you choose. The two resets, reset the form to default as for the plugin will clear it completely.

  39. How do we skip hidden input?

  40. Lance

    Thank you for this code, it was handy to use on ajax submit. I updated my local version to include the new html5 input types.

  41. This doesn't work for all the HTML5 input types, such as . FYI.

  42. easier way is to call click on the reset button, and then $j('input:checkbox,input:radio').each(function(){
    $j(this).attr('checked',false);
    $j(this).attr('selected',false);}

    not need for so much, keep things simple.

6 Pings

  1. [...] Clearing form data: como borrar los datos en un formulario [...]

  2. [...]   http://www.learningjquery.com/2007/08/clearing-form-data [...]

  3. [...] has already been sumbitted and the form is returned to the browser, I based the solution on the Clearing Form Data post at the  Learning jQuery site. This prevents another trip to the server to reset the [...]

  4. [...] Clearing Form Data » Learning jQuery - Tips, Techniques, Tutorials [...]

Sorry, but comments for this entry are now closed.