I know that form.reset()
will reset all form fields to their default values, but how does that work?
Is it the browser's DOM implementation? i.e. the browser knows what were the last values sent from the server in last postback/get and when reset()
is called the browser resets those values.
I know that form.reset()
will reset all form fields to their default values, but how does that work?
Is it the browser's DOM implementation? i.e. the browser knows what were the last values sent from the server in last postback/get and when reset()
is called the browser resets those values.
2 Answers
Reset to default 9The DOM spec tells us that it:
...performs the same action as a reset button.
And so off to HTML. According to the latest spec (still a draft!):
When a form element form is reset, the user agent must fire a simple event named reset, that is cancelable, at form, and then, if that event is not canceled, must invoke the reset algorithm of each resettable element whose form owner is form, and broadcast formchange events from form.
Each resettable element defines its own reset algorithm. Changes made to form controls as part of these algorithms do not count as changes caused by the user (and thus, e.g., do not cause input events to fire).
And the "reset algorithm" for input
elements (for instance) is:
...to set the dirty value flag and dirty checkedness flag back to false, set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, set the checkedness of the element to true if the element has a checked content attribute and false if it does not, empty the list of selected files, and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
So basically, reset
sets the value of an input to the current value of its "value" attribute (theElement.getAttribute("value")
), which may be different from its current value
property (theElement.value
). Live example here.
Edit: Oooh, Pekka points us at defaultValue
. Very cool, I'd much rather use that than getAttribute("value")
. Revised live example.
reset
will use the values in the current HTML source code. The Browser does not know anything about the last Request in this Request (that would be a huge security breach).
If the form contains these elements:
<form action="xyz">
<input type="text" name="fieldA" />
<input type="text" name="fieldB" value="Thingy" />
<input type="reset" value="Click me to undo everything" />
<input type="button" onclick="this.form.reset()" value="Click me too" />
</form>
Both buttons will empty the first field and set the value of the second field to Thingy
.
element.defaultValue
attribute for that – Pekka Commented Nov 8, 2010 at 15:36