ptg 327 chapter 11 Working with Forms and Input Devices 11.1 The Document Object Model and the Legacy DOM 0 If you recall from Chapter 1, “Introduction to JavaScript,” a document object model is a way of conceptualizing a Web page where the document is represented as a tree structure. In Chapter 10, “It’s the BOM! Browser Objects,” we addressed the browser object model (BOM). The properties and methods of different browsers vary because there is no stan- dard for defining what a browser does. The DOM, on the other hand, deals specifically with a document, and there are now standards that dictate how the objects in an HTML (or XML) page should be represented. The industry standard DOM is discussed in full in Chapter 15, “The W3C DOM and JavaScript.” Before the W3C created a standard way to represent an XML/HTML document and all of its elements (DOM Levels 1, 2, and 3) there was a DOM, now called the Legacy Dom 0, invented by Netscape at the same time they created JavaScript. This DOM allowed developers to manipulate and query the content of a Web page, particularly forms and images, and it is still supported by all browsers even if they are DOM 1, 2, or 3 compliant. So if we have a better, newer, and more versatile DOM, why use the old DOM at all? Because the Legacy DOM is still more practical and easier to use when it comes to dealing with forms, images, links, and anchors. (In addition, DOM 0 is useful in searching for an element by its name with index values, removing and adding option elements from a select list, and using the elements[] array to work with input devices, such as buttons and textboxes.) When an HTML document has been completely loaded, the browser represents it as a tree structure where all elements in the page are objects. When working with forms, JavaScript creates an array of all forms as it encounters them in the document, where document.forms[0] represents the first form and if there is another form, it is docu- ment.forms[1]. Similarly, all images, links, and anchors on the page are stored in a arrays representing their names, such as document.images and document.links, and so on. With JavaScript, you can go through these arrays in search of the exact image or form that you want to influence using the array syntax we discussed in Chapter 9, “JavaScript Core From the Library of WoweBook.Com ptg 328 Chapter 11 • Working with Forms and Input Devices Objects.” The elements can be accessed in two ways: by name or by number. If, for exam- ple, you name the first form,“form1”, then you can access it by name (associative array) as document.forms[“form1”] or by numeric index value (numeric array) as docu- ment.forms[0]. 11.2 The JavaScript Hierarchy We discussed the window as part of the BOM in the last chapter. The DOM is concerned only with those nodes that make up the document object. Documents contain text, images, forms, links, anchors, and so on. The most commonly used object is the docu- ment object. Subordinate to the document object are another collection of objects, its chil- dren (see Figures 11.1): 1. The anchors object. 2. The images object. 3. The forms object. 4. The links object. Revisiting the Dot Syntax. To refer to an object, you start with the window object (parent), followed by a dot, then the next object in the hierarchy, then another dot, and so on until you reach the desired object; for example, window.location or window.docu- ment.forms[0]. When referencing a child of the window object, it is not necessary to include Figure 11.1 The document model. src elements[]elements[] Submit Checkbox Text elements[] links[] array of Link objects anchors[] array of Anchor objects forms[] array of Form objects images[] array of Image objects document Document object src property From the Library of WoweBook.Com ptg 11.2 The JavaScript Hierarchy 329 the window, because JavaScript knows that the window is at the top of the tree. Instead of saying window.document.bgcolor, you can simply say document.bgcolor. 11.2.1 The Document Itself The document object is a property of the window object, and if the window is partitioned into frames (subwindows), each frame is a property of the window object. Every window (or frame) contains a document object that corresponds to the HTML document shown in the window. This object corresponds mainly to the body of the doc- ument—that is, what is inserted between the <body></body> tags. JavaScript programs manipulate this object to bring life to otherwise dead, static pages. Because the document object is below the window object, the document object can be represented as a property of the window by saying window.document. The forms object is an array of objects below the document object, so the forms object is a property of the document object and is rep- resented as 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. The syntax for describing the background color (bgcolor) property for a document object is shown in the following example: document.bgcolor = "yellow"; Document Properties. The document object is defined when the HTML <body> tag is encountered on the page and stays in existence until the page exits. The <body> tag has a number of attributes that define the appearance of the page. The document object has prop- erties that correspond to the HTML <body> tag attributes, as shown in Tables 11.1 and 11.2. The properties of the document object are shown in the output of Example 11.2. (See Chapter 13, “Handling Events,” for events that are associated with the <body> tag.) Table 11.1 HTML <body> Tag Attributes Attribute What It Specifies alink Color of an active link; that is, while the mouse is on the link. background URL of a background image. bgcolor Background color of the page. fgcolor Text or foreground color. link Color of an unvisited link. vlink Color of a visited link. From the Library of WoweBook.Com ptg 330 Chapter 11 • Working with Forms and Input Devices As shown in the output of Example 11.1 (see Figure 11.2), the document has a large assortment of properties. Most of these properties, those containing the word “Node,” will be used with the standard W3C DOM Levels 1 and 2. The newer versions of the DOM give you the ability to get access to and manipulate all of the HTML/XML elements in the document. Table 11.2 Some document Object Properties Property What It Describes bgColor, fgColor Determines the background color and text color, related to the HTML <body> tag. cookie Allows reading and writing HTTP cookies (see Chapter 16, “Cookies”). domain A security property for Web servers in the same domain. lastModified A string with the date when the page was last modified. linkColor, alinkColor, vlinkColor Determines the color of unvisited links, active links, and visited links, respectively; related to link attributes of the HTML <body> tag. location The URL of the document (deprecated). referrer URL of the document that linked the browser to this document. title The title of the current document, related to the text between the <title></title> tags found in the head of the document. URL A string containing the URL of the document. EXAMPLE 11.1 <html> <head><title>Looping through Object Properties</title></head> <body> <script type="text/javascript"> 1 var props=new Array(); 2 for ( var property in window.document){ 3 props.push(property); } 4 for(i=0;i<props.length; i++){ 5 document.write( props[i] + " "); if( i>0 && i%4 == 0 ){ document.write("<br />"); } } </script> </body> </html> From the Library of WoweBook.Com ptg 11.2 The JavaScript Hierarchy 331 Using the document Object Properties in JavaScript. Example 11.2 demon- strates how the properties that describe the document are used in a JavaScript program. The write() method displays a description of each of these properties as they pertain to the current document. The background color is silver, the text is forest green, the unvis- ited link is blue, and the visited link is purple. EXPLANATION 1 A new array object called props is created with the Array() constructor. 2 The for/in loop allows you to enumerate (list one by one) the properties of an ob- ject, in this case the document object. The body of the for/in loop is executed once for each property of the document object. 3 Each time through the loop, a new property of the document object is pushed onto the props array. 4 This for loop iterates through the props array to list the properties that were as- signed to it. 5 Each property of the document object is displayed in groups of three. The output differs somewhat on different browsers. Figure 11.2 Partial output showing the document’s properties. From the Library of WoweBook.Com ptg 332 Chapter 11 • Working with Forms and Input Devices EXAMPLE 11.2 <html> <head><title>Document Object Properties</title></head> <body bgcolor="silver" text="forestgreen" link="blue" vlink="purple"> <font face="arial" size="+2"> <script type="text/javascript"> var beg_tag="<em>"; end_tag="</em><br />"; document.write("The location of the document"+ beg_tag + 1 document.location + end_tag); document.write("The document's title: "+ beg_tag+ 2 document.title + end_tag); document.write("The background color: "+ beg_tag+ 3 document.bgColor + end_tag); document.write("The link color is: "+ beg_tag+ 4 document.linkColor + end_tag); document.write("The text color is: "+ beg_tag+ 5 document.fgColor + end_tag); document.write("The document was last modified: "+ beg_tag + 6 document.lastModified + end_tag); </script> 7 <a href="thanks2.html">Thanks!</a> </font </body> </html> EXPLANATION 1 This property contains the location of the document; that is, the full path name to the document. 2 This property contains the title of the document, shown in the title bar at the top of the window. 3 This property describes the hexadecimal color of the document’s background, in this example, silver. 4 This property describes the hexadecimal color of links, blue in this example. 5 This property describes the hexadecimal color of the text, forest green in this example. 6 This displays the date and time when the document was last modified. 7 The link will change color from blue to purple once it has been visited. Complete output is shown in Figure 11.3. Clicking this link opens another page called “thanks2.html” displayed in Figure 11.4. From the Library of WoweBook.Com ptg 11.2 The JavaScript Hierarchy 333 The document Object Methods. The document object has methods to tell the object how to behave or what to do. Table 11.3 lists these methods. We have used the write() and writeln() methods throughout this text to send output to the screen dynam- ically, as shown here: document.writeln("<h2>Welcome to the JavaScript World!</h1>"); Methods, like properties, use the dot syntax to define the object they are manipulat- ing; for instance, document.clear() or window.open(). (The parentheses differentiate a method from a property.) Figure 11.3 Document properties: Link turns purple after “thanks.html” has been visited. Figure 11.4 After the user clicks the link, this page is displayed. Table 11.3 Methods of the document Object Method What It Does clear() Clears the current document window. close() Closes the document window for writing. Continues From the Library of WoweBook.Com ptg 334 Chapter 11 • Working with Forms and Input Devices 11.3 About HTML Forms At the heart of the Web is the form. It is used to pass information from the browser to the server. Anytime you go online and order a book, trade at an auction, fill out a survey, or send an e-mail using a Web browser, you are working with a form. An HTML form offers you a number of ways to accept input, such as radio buttons, checkboxes, popup menus, hidden fields, and textboxes; these are called virtual input devices or controls. Once the form has been filled out by a user, it normally is sent to a server where the input is processed by a server-side program, such as a Java servlet, CGI, ASP.NET, or PHP application. It is important to understand how the form data is col- lected and sent to the server and then what role JavaScript has in this process. 11.3.1 Attributes of the <form>Tag All forms are in HTML documents. They begin with a <form> tag and its attributes, fol- lowed by the input fields where the user enters form information, and end with a </form> tag. <form name="form1" id="form1" action="URL to server program" method="post"> <input type="text" name="town" id="town" /> (continue here with body of the form including input devices for filling out the form; see Table 11.4 for a complete example). </form> focus() Brings the document into focus. getElementById() Returns a reference to the first object with the specified ID. getElementsByName() Returns a collection of objects with the specified name. getElementsByTagName() Returns a collection of objects with the specified tag name. open() Begins a new document, erasing the old one. write() Writes and appends text into the current document. writeln() Same as write(), but appends a newline if in a <pre> tag. Table 11.3 Methods of the document Object (continued) Method What It Does From the Library of WoweBook.Com . WoweBook.Com ptg 11.2 The JavaScript Hierarchy 331 Using the document Object Properties in JavaScript. Example 11.2 demon- strates how the properties that describe the document are used in a JavaScript program and so on. With JavaScript, you can go through these arrays in search of the exact image or form that you want to influence using the array syntax we discussed in Chapter 9, JavaScript Core . by numeric index value (numeric array) as docu- ment.forms[0]. 11.2 The JavaScript Hierarchy We discussed the window as part of the BOM in the last chapter. The DOM is concerned only with those