Clear a form with jQueryClear 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.

Section 1


Section 2

Section 3

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:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus