Skip to content

Instantly share code, notes, and snippets.

@jasontucker
Created October 30, 2012 16:53
Show Gist options
  • Save jasontucker/3981500 to your computer and use it in GitHub Desktop.
Save jasontucker/3981500 to your computer and use it in GitHub Desktop.
Clear form data - jQuery
//Need to clear all form data? Here’s a handy function to do it.
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;
});
};
// Source: http://www.jquery4u.com/forms/jquery-function-clear-form-data/#.UI02J2knDF8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment