Clearing and resetting forms with jQuery

This code snippet looks at how to reset and clear a form using jQuery. The difference between these two options is that 'resetting' will change all form elements back to their original values as they were when the page was loaded, whereas the objective of clearing a form is to remove all values so fields are blank or unset.

HTML form example

To show a practical example we'll start with a simple HTML form that has a few different form elements:

<form id="my-form">
    <div>
        <label for="name">Name</label>
        <input type="text" id="name" name="name" value="Wolfgang" />
    </div>

    <div>
        <label for="single">Single</label>
        <input type="checkbox" id="single" name="single" checked />
    </div>

    <div>
        <fieldset>
            <legend>Language</legend>
            <label for="english">English</label> <input type="radio" id="english" name="language" checked />
            <label for="french">French</label> <input type="radio" id="french" name="language" />
            <label for="german">German</label> <input type="radio" id="german" name="language" />
        </fieldset>
</div>

<div>
    <label for="about">About</label>
    <textarea name="about"></textarea>
</div>

<div>
    <input type="submit" value="Send" />
    <input type="button" id="reset-form" value="Reset" />
    <input type="button" id="clear-form" value="Clear" />
</div>
</form>

At the end of this form we've placed two additional button options along side submit to either reset or clear the form.

jQuery clear and reset click events

Next we add two click events to the buttons. The 'reset' button simply calls the javascript 'reset' function, and the 'clear' button searches for all form elements matching a certain type (e.g. text and password inputs) and sets their value to blank, or unchecks them for radio buttons and checkboxes.

$(document).ready(function()
{
    $('#reset-form').on('click', function()
    {
        $("#my-form").trigger("reset");
    });

    $('#clear-form').on('click', function()
    {
        $('#my-form').find('input:text, input:password, select, textarea').val('');
        $('#my-form').find('input:radio, input:checkbox').prop('checked', false);
    });
});

Demo

Language

 

Sign Up
comments powered by Disqus
Sign Up

Popular Tags

350x250

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.