Wipe all elements in a form with Javascript

Javascript has a nifty method associated with the form DOM object called reset(). Using this method will revert all values of the form's associated input controls to the values they contained when the page was last sent to the user's browser. That's great... but if you want to revert the values to nothing, then some scripting is required:

Javascript code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
function clearForm(formId)  
{  
    // confirm action  
    if(!confirm("Are you sure you want to clear the form?"))  
        return;

    var a; // iterator  
    var whichForm = document.getElementById(formId); // form to clear  
    var elementType; // "type" attribute of current element

    // reset the form (this will clear INPUT TYPE="file" controls)  
    whichForm.reset();

    // clear INPUT elements  
    var inputElements = whichForm.getElementsByTagName("input");

    for(a = 0; a < inputElements.length; elementType = inputElements[a++].attributes.getNamedAttribute("type"))  
    {  
        // use proper clear behavior for given input type  
        switch(elementType)  
        {  
            // TEXT inputs  
            case "text":  
            // HIDDEN inputs (may want to disable this)  
            case "hidden":  
                inputElements[a].value = "";  
                break;  
            // CHECKBOX inputs  
            case "checkbox":  
            // RADIO inputs  
            case "radio":  
                inputElements[a].checked = false;  
                break;  
            case default:  
                continue;  
                break;  
        }  
    }

    // clear TEXTAREA elements  
    var inputElements = whichForm.getElementsByTagName("textarea");  
    for(a = 0; a < inputElements.length; inputElements[a++].value = "");

    // clear OPTIONs  
    var inputElements = whichForm.getElementsByTagName("option");  
    for(a = 0; a < inputElements.length; inputElements[a++].selected = false);  
}

If you are using the hidden input controls for something other than tracking user input on the form, you may want to comment out the line case "hidden": in the switch(elementType) block.

Comments !