Short jQuery script to clear form

Clearing a form can sometimes be a bit of a hassle since there’s no native functionality for that – the “reset” button resets the form fields to their default values, not clears them. The script below takes care of exactly that, taking into account some of the newer input types (such as “email” and “date”). It is written as an extension to jQuery, meaning you can use it like a jQuery method, something like this `$(‘#myform’).clearForm()`, but it can easily be written as a regular stand alone function.

// .clearForm - clears form fields from any values
$.fn.clearForm = function () {
	var el = this.find('input, select, textarea'),
		len = el.length,
		i = 0;
	for (; i  len; i++) {
		switch (el[i].type) {
			case 'text':
			case 'password':
			case 'select-one':
			case 'select-multiple':
			case 'textarea':
			case 'email':
			case 'date':
			case 'number':
			case 'phone':
			case 'checkbox':
			case 'radio':
				el[i].checked = false;
// end .clearForm

To clear form the function simply iterates over all input, select and textarea children of a form (or any container with form elements) and sets the value to blank, or for radio and checkboxes it sets the checked status to false.

It's not very "smart", because it will attempt to clear form elements on any element, even if it's not a form, or anything that can even contain form elements, but then again there's not much that can go wrong with it either. If it can't find any input, select or textarea elements it will just do nothing.

One Comment

  1. Web Design Company India
    February 13, 2013

    This was really such a great and fun article for me to read. I really do think that I have learned so much. This was really awesome.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>