Clear a form with jQuery
Posted June 19th, 2009 in Javascript
A few weeks ago I posted how to clear a form with Javascript and in this post look at how to do the same thing but using jQuery, which makes the code required to do it much more condensed.
Note that an HTML form can be reset using a reset button but this resets the form back to its original state, whereas you may want to be able to clear all the fields in the form.
Example
Here's an example to show what I'm talking about. If you modify any of the fields and then click "Reset" the form will reset back to its original state. Clicking "Clear All" will clear all the fields. Clicking "Clear Section X" will clear only that section in the form. I've used fieldsets and legendsto mark the sections but they just as easily be divs or tables etc.
The jQuery
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
The buttons
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
Note that you can can either pass in a reference to an element (e.g. this.form in the above) or the #id of the set of elements to apply the reset to.
Related posts:
- Changing the default text value on focus with jQuery (Friday, May 29th 2009)
- Clear a form with Javascript (Friday, May 22nd 2009)
- Clear upload file input field with jQuery (Sunday, May 10th 2009)
- Fieldset and legend tags in HTML forms (Saturday, May 2nd 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- Clearing the default value of text input with Javascript (Tuesday, June 17th 2008)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
