You are here: Home » All Posts » Javascript Form Handling » Using JavaScript to reset or clear a form

Using JavaScript to reset or clear a form

in Javascript Form Handling

Using an HTML ‘Reset’ button is an easy way to reset all form fields to their default values. For instance, the code snippet below shows an <input> field of type “reset”, which on being clicked resets all the form fields:

<input type="reset" value="Reset Form">


In fact, we could also use the form’s reset() method to achieve the same effect, using a simple button element:

<input type="button" value="Reset Form" onClick="this.form.reset()" />

These methods are very convenient to use, but they do not provide the functionality of clearing all the fields, including their default values. In order to achieve this, we would need to write a JavaScript function that would clear each individual field’s value.

Simple example for clearing all form elements using JavaScript

Let us look at an example of a simple form

<form name="data_entry" action="#">

Company Name: <input type="text" size="35" name="company_name">

Select Business Type: <input type="radio" name="business_category" value="1"> Manufacturer
<input type="radio" name="business_category" value="2"> Whole Sale Supplier
<input type="radio" name="business_category" value="3"> Retailer
<input type="radio" name="business_category" value="4"> Service Provider

Email Address: <input type="text" size="30" name="email">

Keep Information Private: <input type="checkbox" name="privacy">

<input type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();">

<input type="button" name="clear" value="Clear Form" onclick="clearForm(this.form);">
</form>

As you can see, the first button simply resets all the fields using this.form.reset() as described earlier. Let us now write the JavaScript function that behaves as the onClick handler for the second button in the above form.

  1. In this function, we would first need to acquire a reference to all the elements in the form object:
  2. var frm_elements = oForm.elements; 

    where, oForm is a reference to the form object passed to the function using this.form as shown in the form above. oForm.elements is now a Javascript array that holds a reference to each of the form elements.

  3. We would then have to iterate over the individual form element objects of the frm_elements array (Step 1), using a for-loop construct:
  4. for(i=0; i<frm_elements.length; i++)
    {
        // code for accessing each element goes here
    }
    
  5. We can find out the type of each form element in the frm_elements array by retrieving it’s type property:
  6. field_type = frm_elements[i].type.toLowerCase(); 
  7. If frm_elements[i] holds a reference to any of the <text>, <password>, <textarea> and <hidden> elements, it’s value can be cleared by simply setting it to an empty string:
  8. frm_elements[i].value = ""; 

    In case of radio and checkbox elements, we would use a different approach:

    if (frm_elements[i].checked)
    {
        frm_elements[i].checked = false;
    }
    

    If frm_elements[i] is an object of the type select (either select-one or select-multi), we can set the selectedIndex property to -1:

    frm_elements[i].selectedIndex = -1;
  9. We can group these techniques by using a javascript switch, in this way:
  10. for (i = 0; i < frm_elements.length; i++)
    {
        field_type = frm_elements[i].type.toLowerCase();
        switch (field_type)
        {
        case "text":
        case "password":
        case "textarea":
        case "hidden":
            frm_elements[i].value = "";
            break;
        case "radio":
        case "checkbox":
            if (frm_elements[i].checked)
            {
                frm_elements[i].checked = false;
            }
            break;
        case "select-one":
        case "select-multi":
            frm_elements[i].selectedIndex = -1;
            break;
        default:
            break;
        }
    }
    

Have a look at the demo to see how it works, and compare the result of clicking the reset button and the button with the custom onClick handler that we have just coded. You can also download the code from here.

Illustrating the difference between resetting and clearing a form

As the above demo illustrates, the two buttons function similarly, for this particular form, because none of the values of the elements in this form are set on page load. So the difference between the functioning of the two buttons is not visible. Let us set default values for some of the form elements. For instance, the following snippet of code sets the default for the radio element named “business_category” to the value 3.

<input type="radio" name="business_category" value="1">Manufacturer
<input type="radio" name="business_category" value="2">Whole Sale Supplier
<input type="radio" name="business_category" value="3" checked>Retailer
<input type="radio" name="business_category" value="4">Service Provider

Likewise, we can also set defaults for a few other form elements. See this demo, for an example and compare it with the previous one. As you must have noticed, the difference is now obvious, as the Reset button does not clear the default values, unlike the other button, which does.

Download the code

Be Sociable, Share!
  • azira

    But how to clear img in the form? any idea?

  • shareef hiasat

    this is professional
    am so glad with this JS code

  • Alex

    Okay, the part in my post where it says “…etc.” I was trying to include the following html lines:
    form action=”config.php” method=”POST”
    input type=”hidden” name=”type” value=”commit_changes”

    … but I forgot to remove the angle brackets, so they got interpreted instead of posted.

  • Alex

    (sorry – last post got truncated)

    Function works great — with one oddity. After clearing the form, if I fill the form out again and click on the Submit button, the form’s value for $_POST[‘type’] is cleared also. How to retain that setting? I set it originally like this:

    …etc.

    When config.php gets invoked normally (no form reset), $_POST[‘type’] = “commit_changes”
    When config.php gets invoked after a form reset, $_POST[‘type’] = “”
    How can I restore this setting?

  • Alex

    Function works great — with one oddity. After clearing the form, if I fill the form out again and click on the Submit button, the form’s value for $_POST[‘type’] is cleared also. How to retain that setting? I set it originally like this:

    …etc.

    When config.php gets invoked normally (no form reset), $_POST[‘type’] = “commit_changes”
    When config.php gets invoked after a form reset, $_POST[‘type’] = “”
    How can I restore this setting?

  • Chad

    Shouldn’t “select-multi” be “select-multiple”?

  • http://www.tuzlacicekci.org tuzla çiçekçi

    Nice.. Thank you.

  • ~Red

    You should include ‘if(frm_elements[i].type != undefined) { . . .’ as the code will error out if there are fieldsets, etc. in the form. Could also drop the temp ‘field_type’ variable and place ‘frm_elements[i].type.toLowerCase()’ inside the switch statement (‘switch (frm_elements[i].type.toLowerCase()) { . . .’) in favor of optimization.

    Very helpful function though.

  • Seegreen

    How to clear all the error messages when putting a reset button next to submit button.

  • Wonka

    As far as the clearForm function, the downloaded example would not work for me.  Must be some sort of error.  Everything looks OK.  In fact, when I go to the example on the download page, the example does not work.

  • David

    Perfect !! Thank you

  • http://aamc.org Farhad

    Thanks very help ful but you have but you have a syntax error elements should be frm_elements

    • prasanth

      Thanks. Corrected now.

  • http://blog.inef.web.id Budi Susilo

    Thanks,it’s very helpfull

  • http://www.vivekmodi.com vivek

    thanks this can really help me out

  • Edip

    Thank you very much who has written this article, it is what I wanted, clear language and simple, even dont have to know about javascript…

Previous post:

Next post: