Home / Clear a form with Javascript

Clear a form with Javascript

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. This post shows how to do this with Javascript. This uses regular Javascript; I will show how to do this with jQuery in another post.

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 Javascript

Here's the Javascript code which does the above:

function clear_form_elements(ele) {

    tags = ele.getElementsByTagName('input');
    for(i = 0; i < tags.length; i++) {
        switch(tags[i].type) {
            case 'password':
            case 'text':
                tags[i].value = '';
                break;
            case 'checkbox':
            case 'radio':
                tags[i].checked = false;
                break;
        }
    }
   
    tags = ele.getElementsByTagName('select');
    for(i = 0; i < tags.length; i++) {
        if(tags[i].type == 'select-one') {
            tags[i].selectedIndex = 0;
        }
        else {
            for(j = 0; j < tags[i].options.length; j++) {
                tags[i].options[j].selected = false;
            }
        }
    }

    tags = ele.getElementsByTagName('textarea');
    for(i = 0; i < tags.length; i++) {
        tags[i].value = '';
    }
   
}

The buttons

And here are the buttons:

<input type="reset" value="Reset" />
<input type="button" value="Clear All" onclick="clear_form_elements(this.form)" />
<input type="button" value="Clear Section 1" onclick="clear_form_elements(document.getElementById('example_section_1'))" />
<input type="button" value="Clear Section 2" onclick="clear_form_elements(document.getElementById('example_section_2'))" />
<input type="button" value="Clear Section 3" onclick="clear_form_elements(document.getElementById('example_section_3'))" />

Some notes

I think the above code is fairly self explanatory; it finds all the input, then select then textarea tags and clears their values, unchecks boxes etc. You can then either specify a specific form to clear by assigning "clear_form_elements(this.form)" to a button in the form, or to the form elements withinin a specific element e.g. clear_form_elements(document.getElementById('example_section_1'))