Tải bản đầy đủ (.pdf) (19 trang)

Forms and form Elements

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (216.71 KB, 19 trang )

Chap s and F
Elements
As we've seen in examples throughout thi use
almost all JavaScript programs. This chapter explains th programming with
forms in JavaScript. It is assumed that you are already so
creation of H s and with the inp ents tha
want to refer to a good book on HTML.
[1]
ter 15. Form orm
s book, the of HTML forms is basic to
e details of
mewhat familiar with the
t they contain. If not, you mayTML form ut elem
ent-side
lists the HTML syntax along with the JavaScript syntax m elements; you
may find these useful for quick reference.
[1]
Such as HTML: T usciano and Bill Kennedy (O'Reilly
If you are already familiar with server-side programmin ay
find that things are done differently when forms are used with JavaScript. In the server-
side model, a it contains is subm
once. The emphasis is on processing a complete batch o
producing a new web page in response. With JavaScript
different. In phasis is not on form submission and processing
but instead on event handling. A form and all input elem
that JavaScript can use to respond to user interactions w
on a checkbox, for example, a JavaScript program can re
event handler and m e value
of the form.
With server- L form isn't useful u
unless it has only a single ield and allows the as a


shortcut for subm Submit button is never
necessary (unless the JavaScript program is working wit
program, of cript, a form can have any number of push buttons with
event handle number of actions when clicked. In previous chapters,
The cli reference section of this book
for forms and for
he Definitive Guide, by Chuck M ).
g using HTML forms, you m
itted to the web server all at
f input data and dynamically
form with the input data
, the programming model is quite
JavaScript programs, the em
ents in it have event handlers
ithin the form. If the user clicks
ceive notification through an
displayed in some other elementight respond by changing th
side programs, an HTM
text input f
nless it has a
Submit button (or
user to press the Return key
ission). With JavaScript, on the other hand, a
course). With JavaS
rs that perform any
h a cooperating server-side
we've seen some of the possible actions that such buttons can trigger: replacing one
image with another, using lay a new web page,
opening a new browser window, and dynamically generating a new HTML document in
an ndow or f in hapter, a

can even trigger a form itted.
As we've see t this book, event h a
central element of any interesting JavaScript program. A
event handlers (excluding the event handlers of the Link
forms or form his chapter introduces the Jav object and the
various JavaScript objects that represent form elements. It concludes with an example
that illustrates how you can use JavaScript to validate user input on the client before
ar
ts of the form.
cument. So
ent
nce. The action ,
properties correspond directly to the
action, encoding,
es of the <form> tag. These properties and attributes are all
they are therefore useful only when the form is actually submitted to a server-
r
the
location property to load and disp
other wi rame. As we'll see later
to be subm
this c JavaScript event handler
n in examples throughou andlers are lmost always the
nd the most commonly used
object) are those used with
aScript Form elements. T
submitting it to a server-side program running on the web server.
15.1 The Form Object
The JavaScript Form object represents an HTML form. Forms are always found as
elements of the forms[] array, which is a property of the Document object. Forms appe

in this array in the order in which they appear within the document. Thus,
document.forms[0] refers to the first form in a document. You can refer to the last form
in a document with the following:
document.forms[document.forms.length-1]
The most interesting property of the Form object is the elements[] array, which contains
JavaScript objects (of various types) that represent the various input elemen
Again, elements appear in this array in the same order they appear in the do
you can refer to the third element of the second form in the document of the curr
window like this:
document.forms[1].elements[2]
The remaining properties of the Form object are of less importa
,
method, and targetencoding
method, and target attribut
used to control how form data is submitted to the web server and where the results are
displayed;
side program. See the client-side reference section for an explanation of the properties, o
see a book on HTML or CGI programming
[2]
for a thorough discussion of the attributes.
What is worth noting here is that these Form properties are all rea
JavaScript program can dynamically set their values in order to change the way the form
d/write strings, so a
is submitted.
[2]
Such as CGI Programming on the World Wide Web, by Shishir Gundavaram (O'Reilly).
In the days before JavaScript, a form was submitted with a special-purpose Submit
ecial-purpose Reset button. The
) and (as of JavaScript 1.1)
reset( ) e. Invoking the submit( ) method of a Form

resets the form elements.
t provides the
avaScript 1.1) the onreset
d just before the form
avoid
it
ine click on a Submit button. Calling the submit( )
the onsubmit handler.
Th event handler is similar to the handler. It is invoked just before
false. This allows a JavaScript program to ask for confirmation of the reset, which can
be a good idea when the form is long or detailed. You might request this sort of
confirmation with an event handler like the following:
<form...
onreset="return confirm('Really erase ALL data and start over?')"
>
Like the onsubmit handler, onreset is triggered only by a genuine Reset button. Calling
) method of a form does not trigger onreset.
ects with which we create graphical user
interfaces for our JavaScript programs.
Figure 15-1
button, and form elements had their values reset with a sp
JavaScript Form object supports two methods, submit(
, that serve the same purpos
submits the form, and invoking reset( )
To accompany the submit( ) and reset( ) methods, the Form objec
onsubmit event handler to detect form submission and (as of J
event handler to detect form resets. The onsubmit handler is invoke
is submitted; it can cancel the submission by returning false. This provides an
to check the user's input for errors in order toopportunity for a JavaScript program
submitting incomplete or invalid data over the network to a server-side program. We'll

see an example of such error checking at the end of this chapter. Note that the onsubm
handler is triggered only by a genu
form does not triggermethod of a
e onreset onsubmit
the form is reset, and it can prevent the form elements from being reset by returning
the reset(
15.2 Defining Form Elements
HTML form elements are the primitive obj
shows a complex form that contains
at least one of each of the basic form elements. In case you are not already familiar with
each type ofHTML form elements, the figure includes a numbered key identifying
ample 15-1element. We'll conclude this section with an example (Ex ) that shows the
5-1HTML and JavaScript code used to create the form pictured in Figure 1 and to hook
up event handlers to each of the form elements.
Figure 15-1. HTML form elements
Table 15-1 lists the types of form elements that are availa
ipt programmers. The first column of the table nam
ble to HTML designers and
es the type of form element,
s
en, each Form object has an elements[] array that contains the objects that
m another. By examining the type property of
an unknown form element, JavaScript code can determine the type of the element and
this done in Example 15-2
JavaScr
the second column shows the HTML tags that are used to define elements of that type,
third column lists the value of the type property for each type of element. Aand the
've sewe
represent the form's elements. Each of these elements has a type property that can be
used to distinguish one type of element fro

figure out what it can do with that element. (We'll see , at the
ble provides a short description of
each element and also lists the most important or most commonly used event handler for
the
various types of elements are available in the client-side reference section, under the
name listed in the first column of Table 15-1
end of the chapter.) Finally, the fourth column of the ta
that element type.
We'll talk more about form elements later in this chapter. Complete details about
. Although each type of form element has a
separate reference page, note that most of the elements are created with HTML
<input>
tags and are, in fact, all Input objects. The client-side reference page named "Input" lists
the features that all these elements have in common, and the type-specific pages provide
specific details about working with a particular type of form element. Note that the names
Button, Checkbox, and so on from the first column of the table may not correspond to
any actual object in a client-side JavaScript implementation, and note also that the DOM
standard does not define any interfaces with these names. Still, each type of form element
has a distinct appearance and distinct behavior, and it is useful to treat them as separate
types, at least for the purposes of the client-side reference section. In the DOM reference
section you can find material about forms and their elements under the names
"HTMLFormElement," "HTMLInputElement," "HTMLTextAreaElement,"
"HTMLSelectElement," and "HTMLOptionElement."
Table 15-1. HTML form elements
Object HTML tag
type
property
Description and events
Button
"button">

or <button
"button"
A push button; onclick.
<input type=
type="button">
Checkbox
<input
type="checkbox">
"checkbox"
A toggle button without radio-
button behavior; onclick.
FileUpload
<input type="file">
"file"
An input field for entering the
name of a file to upload to the
web server; onchange.
Hidden
<input type="hidden">
"hidden"
not visible to the user; no event
handlers.
Data submitted with the form but
Option
<option>
none
A single item within a Select
object; event handlers are on the
Select object, not on individu
Option objects.

al
Password
<input
type="password">
"password"
An input field for password
entry -- typed characters are not
visible; onchange.
Radio
<input type="radio">
"radio"
tton with radio-
button behavior -- only one
selected at a time; onclick.
A toggle bu
Reset
<input type="reset"> or
"reset"
A push button that resets a form;
<button type="reset">
onclick
.
Select
<select>
"select-one"
A list or drop-down menu fro
which one item may be selec
m
ted;
onchange. (See also Option

object.)
Select
<select multiple>
"select-
multiple"
A list from which multiple items
may be selected; onchange. (See
also Option object.)
Submit
or
"submit"
its a
form; onclick.
<input type="submit">
A push button that subm
<button
type="submit">
Table 15-1. HTML form elements
Object HTML tag
type
property
Description and events
Text
<input type="text">
"text"
A single-line text entry field;
onchange.
Textarea
<textarea>
"textarea"

A multiline text entry field;
onchange.
Now th
used to
at we've taken a look at the various types of form element and the HTML tags
create them, Example 15-1 shows the HTML code used to create the form shown
in Figure 15-1. Although the example consists primarily of HTML, it also contains
JavaScript code used to define event handlers for each of the form elements. You'll notice
event handlers are not defined as HTML attributes. Instead, they are JavaScript
ns assigned to the properties of the objects in the form's elements[] array. The
event h he
various form elem
know to understand what the report( ) function is doing.
ple 15-1. An HTML form containing all form elements
<form name="everything"> <!-- A one-of-everything
HTML form... -->
<table border="border" cellpadding="5"> <!-- in a big HTML table -->
<tr>
<td>Username:<br>[1]<input type="text" name="username"
size="15"></td>
<td>Password:<br>[2]<input type="password" name="password"
size="15"></td>
<td rowspan="4">Input Events[3]<br>
<textarea name="textarea" rows="20" cols="28"></textarea></td>
<td rowspan="4" align="center" valign="center">
[9]<input type="button" value="Clear" name="clearbutton"><br>
[10]<input type="submit" name="submitbutton" value="Submit"><br>
[11]<input type="reset" name="resetbutton"
value="Reset"></td></tr>
<tr>

<td colspan="2">
Filename: [4]<input type="file" name="file" size="15"></td></tr>
<tr>
<td>My Computer Peripherals:<br>
[5]<input type="checkbox" name="peripherals" value="modem">56K
ue="tape">Tape
Backup</td>
<td>My Web Browser:<br>
[6]<input type="radio" name="browser" value="nn">Netscape<br>
that the
functio
andlers all call the function report( ), which contains code that works with t
ents. The next section of this chapter explains everything you need to
Exam
Modem<br>
[5]<input type="checkbox" name="peripherals"
value="printer">Printer<br>
[5]<input type="checkbox" name="peripherals" val
[6]
Explorer<
<input type="radio" name="browser" value="ie">Internet
br>
value=
<tr
<td>My Hobbies:[7]<br>
<select multiple="multiple" name="hobbies" size="4">
ption value="programming">Hacking JavaScript
option value="surfing">Surfing the Web
<option value="caffeine">Drinking Coffee
<

</table>
</form>
="center"> <!-- Another table--the key to the one
above -->
<table border="4" bgcolor="pink" cellspacing="1" cellpadding="4">
<tr>
<td align="center"><b>Form Elements</b></td>
d>[4] FileUpload</td> <td>[5] Checkbox</td></tr>
<td>[6] Radio</td> <td>[7] Select (list)</td>
<td>[8] Select (menu)</td> <td>[9] Button</td>
<td>[10] Submit</td> <td>[11] Reset</td></tr>
</table>
</div>
<script>
// This generic function appends details of an event to the big
Textarea
// element in the form above. It is called from various event handlers.
function report(element, event) {
var elmtname = element.name;
if ((element.type == "select-one") || (element.type == "select-
multiple")){
value = " ";
for(var i = 0; i < element.options.length; i++)
if (element.options[i].selected)
value += element.options[i].value + " ";
}
else if (element.type == "textarea") value = "...";
else value = element.value;
var msg = event + ": " + elmtname + ' (' + value + ')\n';
var t = element.form.textarea;

t.value = t.value + msg;
}
// This function adds a bunch of event handlers to every element in a
form.
[6]<input type="radio" name="browser"
"other">Other</td></tr>
>
<o
<
<option value="annoying">Annoying my Friends
</select></td>
td align="center" valign="center">My Favorite Color:<br>[8]
<select name="color">
<option value="red">Red <option value="green">Green
<option value="blue">Blue <option value="white">White
<option value="violet">Violet <option value="peach">Peach
</select></td></tr>
<div align
<td>[1] Text</td> <td>[2] Password</td> <td>[3] Textarea</td>
<t
<tr>

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×