Clearing Form Data

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.  
  8.     // it's ok to reset the value attr of text inputs,
  9.     // password inputs, and textareas
  10.     if (type == 'text' || type == 'password' || tag == 'textarea')
  11.       this.value = "";
  12.  
  13.     // checkboxes and radios need to have their checked state cleared
  14.     // but should *not* have their 'value' changed
  15.     else if (type == 'checkbox' || type == 'radio')
  16.       this.checked = false;
  17.  
  18.     // select elements need to have their 'selectedIndex' property set to -1
  19.     // (this works for both single and multiple select elements)
  20.     else if (tag == 'select')
  21.       this.selectedIndex = -1;
  22.   });
  23. };

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.

14 Responses to “Clearing Form Data”

  1. Estevão Lucas Says:

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


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

  2. Dave Cardwell Says:

    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. Mike Alsup Says:

    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. yaph Says:

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

  5. Karl Says:

    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. yaph Says:

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

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

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

    Sascha

  9. Mike Alsup Says:

    @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. Sunset Pearl Says:

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

  11. Robsworld Says:

    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. Sudrien Says:

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

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

  13. DrLex Says:

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

    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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <pre> <em> <i> <li> <ol> <strike> <strong> <ul>

IMPORTANT: If you wish to post code examples, please wrap them in <code> tags. Multi-line code should be wrapped in <pre><code> </code></pre> Also, use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.