Main Page

Resetting forms

Resetting forms
If you want to provide the user a way to reset all form fields to their default values, you can use an
HTML Reset button:
<input type=”reset” value=”Reset Values” />
Similar to a Submit button, a Reset button requires no scripting for the browser to know what to do
when it is clicked. Also similar to the Submit button, a
reset
event fires when the button is clicked:
<form method=”post” action=”javascript:alert(‘Submitted’) “ onreset=”alert(‘I am
resetting’) “>
Of course, you can also use the
onreset
event handler to cancel the form reset.
The form does have a
reset()
method that can reset the form directly from script without using a Reset
button:
<input type=”button” value=”Reset” onclick=”document.forms[0].reset()” />
Unlike
submit()
, using
reset()
still fires the
reset
event and the
onreset
event handler is still
executed.
Text boxes
Two flavors of text boxes are used in HTML: a single-line version,
<input type=”text”/>
, and a
multiline version,
<textarea/>
.
The
<input/>
element must have its
type
attribute set to
“text”
in order to display a text box. You
then use the
size
attribute to specify how wide the text box should be in terms of visible characters (for
instance, setting
size
to
“10”
means that only 10 characters are visible at one time). The value attribute
specifies the initial
value
of the text box and the
maxlength
attribute specifies how many characters are
Resetting a form has fallen out of favor among Web developers because an increas-
ing number of users have mistakenly reset the form instead of submitting it (often
the Submit and Reset buttons are next to each other). If a form contains information
in form fields when it is first loaded, a Reset button can be helpful because it resets
the fields to their initial values. For forms that initially load without any information
in form fields, it is recommended to avoid using a Reset button.
You may be wondering why you can’t just use a Submit button and disable it using
onclick
. The answer is that the button actually disables before the form is submit-
ted, which then prevents the form from being submitted at all.
342
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 342


JavaScript EditorFree JavaScript Editor     Ajax Editor


©