How to clear a form?

As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:

Plain Javascript:

function resetForm(form) {
    // clearing inputs
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i<inputs.length; i++) {
        switch (inputs[i].type) {
            // case 'hidden':
            case 'text':
                inputs[i].value="";
                break;
            case 'radio':
            case 'checkbox':
                inputs[i].checked = false;   
        }
    }

    // clearing selects
    var selects = form.getElementsByTagName('select');
    for (var i = 0; i<selects.length; i++)
        selects[i].selectedIndex = 0;

    // clearing textarea
    var text= form.getElementsByTagName('textarea');
    for (var i = 0; i<text.length; i++)
        text[i].innerHTML= '';

    return false;
}

Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.

For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:

<input type="reset" value="Reset" name="reset" onclick="return resetForm(this.form);">

You can test it all here on jsFiddle.

If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):

jQuery(function($) { // onDomReady

    // reset handler that clears the form
    $('form[name="myform"] input:reset').click(function () {
        $('form[name="myform"]')
            .find(':radio, :checkbox').removeAttr('checked').end()
            .find('textarea, :text, select').val('')

        return false;
    });

});

Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.

Play with this here.

Leave a Comment