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:

[js]function clearForm(form) { // iterate over all of the inputs for the form // element that was passed in $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase(); // normalize case // it's ok to reset the value attr of text inputs, // password inputs, and textareas if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ""; // checkboxes and radios need to have their checked state cleared // but should *not* have their 'value' changed else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = -1; }); };[/js]

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

[js]$.fn.clearForm = function() { // iterate each matching form return this.each(function() { // iterate the elements within the form $(':input', this).each(function() { var type = this.type, tag = this.tagName.toLowerCase(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }); };[/js]

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

[js]$.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 (tag == 'select') this.selectedIndex = -1; }); };[/js]

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

[js]$('form').clearForm()[/js]

Or like this:

[js]$(':input').clearForm()[/js]

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