Monday, January 24, 2011

Clearing form data using jquery

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:
 
  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:
 
$(':input').clearForm()
 
or
 
$('form').clearForm()
 
Cheers,
 
Ujjwal Soni