How To Reset a Form Using jQuery

February 20th, 2013 - Posted by Steve Marks to Javascript / jQuery, Web Development.

Let’s imagine that we have the following very simple form containing just one input box, and a link outside the form that, when clicked, should clear the forms inputs:

<form id="myForm">
    <input type="text">
</form>
    
<a href="#" id="resetAnchor">Reset Form</a>

Normally, to reset a form we’d have an input of type ‘reset’ within the form that would empty all the inputs and reset them back to their original state when the page first loaded. This scenario is a little different however, in that we have a control external to the form that we want to use as the trigger.

When I first stumbled across this requirement my first thought was to do the following:

$(document).ready(function() {
    
    $('#resetAnchor').click(function() {
        
        $('#myForm').reset();
        return false;
        
    });
    
});

Here I’m attaching a listener to the click event of the link and attempting to reset the form with ID ‘myForm’. To my surprise, the above code didn’t work and the forms inputs didn’t get cleared.

The Solution

It turns out that there are a couple of alternative solutions here to make this code work. To keep it simple I’ll just show you the method that I used:

$(document).ready(function() {
    
    $('#resetAnchor').click(function() {
        
        $('#myForm')[0].reset();
        return false;
        
    });
    
});

Can you spot the change? By simply changing the line:

$('#myForm').reset();

to:

$('#myForm')[0].reset();

the form now got reset as expected.

This entry was posted on Wednesday, February 20th, 2013 at 5:17 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first