Clear a form with jQueryClear a form with jQuery

Posted June 19th, 2009 in Javascript (Updated February 23rd, 2011)

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.

Please note that an HTML form can be reset using a reset button which resets the form back to its original state, whereas this post clears all the fields in the form to an empty state. To reset a form to its default values refer to my "resetting an HTML form with a reset input button" or "reset an HTML form with Javascript" posts.

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 legends to 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.

Comments are closed

Please note that I have closed comments on this post because too many people seem unable to understand the purpose of this post and continue to post comments showing how to reset a form. This post shows how to clear a form, which as explained at the top of this post, is not the same as resetting a form to its default values.

If you want to reset a form refer to my other posts as linked to in the related posts below.

Related posts:

Comments

blog comments powered by Disqus