Reset an HTML form with Javascript

Posted in Javascript -

After receiving a number of "creative" ways to reset forms with Javascript on my "clear a form with jQuery" post, I've decided to post the correct way to reset a form with Javascript.

Reset vs clear

Interestingly, all the commenters on that post who posted how to reset a form with Javascript failed to understand the purpose of that post. The purpose of the post was to show how to clear the values from all the fields to an empty state, which is not the same as resetting the form to its default state.

If a form field has a default value that was already set in the HTML, calling reset will restore the value to that original value if it has changed since the page was loaded. Obviously if the field was blank, reset will make it blank again. But if it had a value, reset will restore it to that value. Clearing the form will remove all field values no matter what the original value of each field.

Normally it's simply easier to add a reset button to the form, but there may cases where you want to reset the form using code or from an anchor or button outside the form. This is what I show how to do here.

Reset the form with Javascript

Here's an example form. Note that I've assigned both name and id attributes and show how to reset the form using either. Your form ideally needs to have one or the other, although you can access the form using e.g. document.forms[0] but it's not recommended because the number of forms on a page may change.

<form name="myFormName" id="myFormId">
    <input type="text" name="test" value="1234546" />
</form>

And here are a variety of ways to reset the form using Javascript.

Using the id attribute:

document.getElementById('myFormId').reset();

Using the name attribute:

document.myFormName.reset();
document.forms.myFormName.reset();
document.forms['myFormName'].reset();

Or using jQuery, id then name:

$('#myform').get(0).reset();
$('form[name=myform]').get(0).reset();

Now wasn't that easy?



Related posts:


Comments