jQuery Function to All Clear Form Data

Sam Deering
Tweet

Pretty useful jQuery Function to clear all form data which I found on Karl Swedberg’s website. It simply removes all data from the form including text inputs, select boxes, radio buttons, checkboxes etc… There are two versions and the second version is probably more useful as you can apply it directly to the DOM element as a jQuery function.

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;
  });
};

Reset Input Button

You can put a hidden input of type reset and then trigger it to clear the form.

<input type="reset" style="display:none;"/>
$('form > input[type=reset]').trigger('click'); //with a reset button in the form set to display: none;

jQuery Element Function

$.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;
  });
};
//usage
$('#flightsSearchForm').clearForm();

Source

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.