As stated before, because the window object is at the top of the hierarchy, any objects just below it, such as the document or location objects, are window properties and the word window
Trang 11:
Creating FormsHTML
a Create a Web page called Stirbucks that contains a form to order coffee, similar to the order form in Figure C.41
Figure C.41 The Stirbucks Web page order form.
In the action attribute of the initial <FORM> tag, specify a URL that directs the server to a CGI script using the default GET method.
Test your file in a browser.
The CGI script will print the value of the QUERY_STRING environment variable.
Processing FormsCGI
a Write a CGI script that will send back to the user an HTML page that thanks him for his order and tells him the coffee he selected will be
Trang 2The CGI script will handle e-mail Send e-mail to yourself confirming the information that was submitted Design another function to handle e-mail.
a Netscape cookie The cookie should not expire for 1 week (See Figure C.42 )
Figure C.42 Cookie output.
Trang 4Chapter 11 The Document Objects: Forms, Images and Links
Trang 5In Chapter 10 we addressed the browser object model The
properties and methods of different browsers vary since there is
no standard for defining what a browser does The documentobject model (DOM), on the other hand, deals specifically with adocument, and there are now standards that dictate how theobjects in an HTML (or XML) page should be represented TheDOM is a hierarchical tree-like structure,consisting of a
collection of objects, all relating to the document According tothe World Wide Web Consortium (WC3), a DOM is a platform-and language-independent object model that "allows programsand scripts to dynamically access and update the content,
structure, and style of documents."[1] It mimics the structure ofthe document it models When working with JavaScript, the
DOM mimics the HTML document Each element of an HTMLdocument, such as an image, form, link, or button, can be
represented as a JavaScript object, and each object containsproperties and methods to describe and manipulate these
[2] World Wide Web Consortium (W3C),
http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/
Trang 6structure for the core objects, properties, and methods; thesecond defines a set of objects strictly related to HTML In
addition to DOM Level 1, there are two other levels, still in
progress What all that boils down to is that the DOM specifies astandard set of objects that will work with HTML and XML
documents no matter what browser, no matter what scriptinglanguage
Trang 7treeconsists of parents and children called nodes (no, not nerds,but nodes) Each leaf in the tree is called a node The topmost
node, the <html> tag, is the root node The <head> and
<body> tags are child nodes of the <html> parent node If the
nodes are at the same level, they are called siblings, like a realfamily Nodes may have a parent and a number of child nodes.The DOM provides a set of objects, with properties and
methods
11.1.1 The JavaScript Hierarchy
Since the JavaScript document objects are arranged in a DOMhierarchy, each node in the tree can be referenced using the dot
syntax In JavaScript, the window object is at the top of the
Trang 9example, window.location or window.document.forms[0] When referencing a child of the window object it is not necessary to include the window, because JavaScript knows that the window
Trang 10corresponds to the HTML document shown in the window Thisobject corresponds mainly to the body of the documentthat is,
what is inserted between the <body></body> tagsalthough it can also be found in a limited way within the <head></head>
window.document.forms[].
As stated before, because the window object is at the top of the hierarchy, any objects just below it, such as the document or
location objects, are window properties and the word window is
not required; thus, specifying window.document.bgColor is the same as document.bgColor.
attributes, as shown in Tables 11.1 and 11.2 The properties of
Trang 11the document object are shown in the output of Example 11.2.(See Chapter 12, "Handling Events," for events that are
Trang 131 A new array object called props is created with the
Array() constructor.
The for/in loop allows you to enumerate (list one by one) the properties of an object, in this case the document object The body of the for/in loop is executed once for each property of the
document object If a property has been flagged as read-only, it
will not be listed
Each time through the loop, a new property of the document object is pushed onto the props array.
Trang 14JavaScript
The following example demonstrates how the properties thatdescribe the document are used in a JavaScript program The
write() method displays a description of each of these
Trang 16document's background, in this example, silver
This property describes the hexidecimal color of links, blue inthis example
This property describes the hexidecimal color of the text,forest green in this example
This displays the date and time when the document was lastmodified
Trang 183 parent.frames[1].document.close();
Trang 19JavaScript will automatically open a new document and send the output there There are times when this might happen, and you didn't want to overwrite
everything Since the document is parsed top to
bottom, if the browser has finished parsing, then any attempts to write to the document will cause the
whole thing to be overwritten This might happen if you call a function as a result of some event being triggered.
Trang 20in right frame, replacing what was there.
Figure 11.5 After the document in the right-hand frame is closed, the original document reappears
(Netscape 7).
Trang 22method attribute indicates how the form will be processed The get method is the default (and does not need to be specified)
and the post method is the most commonly used alternative The get method is preferable for operations that will not affect
the state of the server; that is, simple document retrieval,
database lookups, and the like The post method is preferred
for handling operations that may change the state of the server,such as adding or deleting records from a database (See
in a name/value pair scheme The value represents the actualinput data Before the server-side program is called, JavaScriptcan be used to validate the data that was entered into the form
Trang 23button name Creates a generic button for user input It has no default action.
size,
maxlength
Creates a text box for user input size specifies the size of the text box maxlength specifies the maximum number of characters
password name,
value
Like text box but input is hidden Asterisks appear in the box to replace characters typed.
checkbox name,
value
Displays a square box that can be checked Creates name/value pairs from user input Multiple boxes can be checked.
Trang 25<p>
Choose your food:<b>
4 <input type="radio" name="choice" value="burger">Hamburger <input type="radio" name="choice" value="fish">Fish
<input type="radio" name="choice" value="steak">Steak
<input type="radio" name="choice" value="yogurt">Yogurt <p>
<b>Choose a work place:</b><br>
5 <input type="checkbox" name="place" value="LA">Los Angeles <br>
<input type="checkbox" name="place" value="SJ">San Jose <br>
<input type="checkbox" name="place" value="SF" checked> San Francisco
Trang 261 This is the beginning of a <form> tag that specifies
where the browser will send the input data and the method that will be used to process it The default
text string that appears in the text box when it is first displayed
by the browser
Trang 27<textarea> tag will produce a rectangle named "comments"
with dimensions in rows and columns (5 rows x 50 columns)
and an optional default value (I was born ).
The user is asked to pick from a series of menu items Thefirst input type is a list of radio buttons Only one button can be
selected at a time The input type has two attributes: a type and a name The value of the name attribute "choice", for
example, will be assigned "burger" if the user clicks on the
Hamburger option choice=burger is passed onto the CGI
program And if the user selects Fish, choice=fish will be
assigned to the query string These key/value pairs are used tobuild a query string to pass onto the CGI program after thesubmit button is pressed
The input type this time is in the form of checkboxes Morethan one checkbox may be selected The optional default box isalready checked When the user selects one of the checkboxes,
attribute is not necessary; it defaults to 1 The pop-up menuinitially displays one option and expands to a menu when thatoption is clicked Only one selection can be made from the
menu If a size attribute is given, that many items will be
displayed If the multiple attribute is given (as <select multiple
name="whatever">), the menu appears as a scrollable list,
displaying all of the options
Trang 28empty fields It can check for a valid credit card number, e-mailaddress, zip code, and so on In addition, rather than havingthe user submit the form, submission can be controlled by
JavaScript with its own submit() method And by naming the
forms, JavaScript can handle multiple forms and input types,respond to user-initiated events, and call functions to handlethe data that was submitted
number of HTML forms and input types such as simple text
boxes, radio buttons, checkboxes, and so on JavaScript
provides objects that parallel HTML tags; for example, the
JavaScript forms object parallels the HTML <form> tag and the JavaScript elements object parallels the input devices such as
radio buttons or checkboxes
In this section we will focus on the structure of the JavaScript
Trang 2912, "Handling Events," you will learn how to catch the form
before it is sent to the server In Chapter 13, "Regular
Expressions and Pattern Matching," you will learn how to checkall the input fields of a form before processing it, using the
magic of regular expressions and pattern matching
The forms[] Array
Since the document contains forms, the forms object is also a property of the document object Every time you create a form
in a given document, the browser creates a unique form object
and assigns it as an element of an array, called the forms[]
array The index value of the array, starting at 0, corresponds tothe order in which the form occurs in the document; the first
Trang 30the field and document.forms[0].elements[0].type references the type of the field, such as submit, reset, button, text, radio,
or checkbox.
If you name the field or input types, those names can be used
Trang 32<form name="form1"> document.forms[0] document.form1
<input type="text" document.forms[0].elements[0] document.form1.yourname name="yourname"
<input type="button"> document.forms[0].elements[1] document.form1.button1 name="button1">
<form name="form2"> document.forms[1] document.form2
<input type="radio"> document.forms[1].elements[0] document.form2.veggie1 name="veggie1">
forms object are listed in Table 11.5 and methods are listed in
Table 11.6 Properties of the elements object are listed in Table
Trang 36Figure 11.9 Name those forms!
Trang 37shown in Table 11.8
Table 11.8 <form> tag elements and properties.
button name, type, value A general purpose GUI button
checkbox checked, defaultChecked, name,
type, value
A set of (or one) clickable boxes allowing multiple selections
FileUpLoad name, type, value A field allowing a file to be submitted as part
reset name, type, value A button that clears and resets the form
Trang 38submit name, type, value, A button used for submitting form data
text defaultValue, name, type, value A rectangular field allowing one line of input
textarea defaultValue, name, type, value A rectangular box allowing multiple lines of
Trang 397 +document.myform.button1.value);
document.write("</em><b><br>Name of second button is:</b><em> " +document.myform.button2.name);
document.write("</em><b><br>Value of button2 field:</b><em> " +document.myform.button2.value);
Trang 40Figure 11.11 What went wrong? Watch your spelling! We tried to reference a form by the
wrong name!
In the following example, the document contains two named
forms, myForm1 and myForm2 Each of the forms contain input
types: the first form contains a text box and the second formcontains three buttons A JavaScript program gets access to theforms and properties by using their names to reference them
Trang 4111 document.write("<br>name: " +
Trang 4212 document.write("value: "
+document.forms[1].elements[i].value+"<br>"); document.write("type: "
Trang 43Figure 11.12 Naming forms and their elements.
Trang 44Submitting an HTML Form Without JavaScript
When the user clicks on a submit button, the form is normallysent right off to the server for further processing by anotherapplication such as a CGI script Before the server gets the
form, its content is gathered by the browser, encoded, and then
sent to the URL address supplied in the action attribute of the form (In the previous examples, the action attribute was not
used because there was no reason to process the sample
forms.) The application on the server side is started up to
Trang 461 The form starts here The action attribute contains
the URL of the server program that will get the form The method being used (how the form will be sent) is
the post method This is the most common method
used with forms.
The user is asked to type something into a text field box.The user is asked to check a box for his place of work
Figure 11.13 A filled-out HTML form awaiting
submission to the server.
Trang 47The image input type gives you another way to submit a form.You can replace the standard submit button with a graphical
image The src attribute must be included to specify the
location (URL) of the image As with other image tags, the alt
attribute (HTML 4.0) should be used to give replacement textfor browsers that cannot load the image Many browsers rely on
<center>
Enter your name:
Trang 48Figure 11.14 An image as a Submit button (IE).
Trang 49event is triggered.
With a form, an event handler allows you to control whether theform is submitted or cleared For example, after the user hasfilled out the form, normally it is sent right off to a CGI, PHP, orASP program on the server side to be processed But if a
Trang 50if(confirm("Are you ready to submit your form? ")){ return true;
Trang 51assigned to the action attribute of the HTML <form> tag.
Trang 52presses the submit button When a function is assigned to the
onSubmit event handler, if the value returned by the function is true, the form will be submitted to the server, but if it returns false, the form will be stopped and the user will be given a