Archive for July, 2007

101Chapter 9Forms and Form ElementsFor the (Freelance web design) visible objects

Friday, July 27th, 2007

101Chapter 9Forms and Form ElementsFor the visible objects in this category, event handlers are triggered from many user actions, such as giving a field focus (getting the text insertion pointer in the field) and changing text(entering new text and leaving the field). Most of your text field actions are triggered by thechange of text (the onchangeevent handler). In modern browsers, event handlers fire inresponse to individual keystrokes as well. Without a doubt, the single most used property of a text-related element is the valueprop- erty. This property represents the current contents of the text element. A script can retrieveand set its content at any time. Content of the valueproperty is always a string. This mayrequire conversion to numbers (see Chapter 6) if text fields are used to enter values for somemath operations. To demonstrate how a text field s valueproperty can be read and written, Listing 9-1 pro- vides a complete HTML page with a single-entry field. Its onchangeevent handler invokes theupperMe()function, which converts the text to uppercase. In the upperMe()function, thefirst statement assigns the text object reference to a more convenient variable: field. A lotgoes on in the second statement of the function. The right side of the assignment statementperforms a couple of key tasks. The reference to the valueproperty of the object(field.value) evaluates to whatever content is in the text field at that instant. That string isthen handed over to one of JavaScript s string functions, toUpperCase(), which converts thevalue to uppercase. The evaluated result of the right-side statement is then assigned to thesecond variable: upperCaseVersion. Nothing has changed yet in the text box. That comes inthe third statement where the valueproperty of the text box is assigned whatever theupperCaseVersionvariable holds. The need for the second statement is more for learningpurposes, so you can see the process more slowly. In practice, you can combine the actionsof steps two and three into one power-packed statement: field.value = field.value.toUpperCase(); Text Object BehaviorMany scripters look to JavaScript to solve what are perceived as shortcomings or behavioralanomalies with text-related objects in forms. I want to single these out early in your scriptingexperience so that they do not confuse you later. First, only the most recent browsers let scripts reliably alter the font, font size, font style, and textalignment of a text object s content. You can access changes through the element s style-relatedproperties (see Chapter 26). Second, most browser forms practice a behavior that was recommended long ago as an informalstandard by Web pioneers. When a form contains only one text inputobject, a press of theEnter/Return key while the text object has focus automatically submits the form. For two or morefields in browsers other than IE5/Mac and Safari, you need another way to submit the form (forexample, a Submit button). This one-field submission scheme works well in many cases, such asthe search page of most Web search sites. But if you are experimenting with simple forms con- taining only one field, you can submit the form with a press of the Enter/Return key. Submittinga form that has no other action or target specified means the page performs an unconditionalreload wiping out any information entered into the form. You can, however, cancel the submis- sion through an onsubmitevent handler in the form, as shown later in this chapter. Also, start- ing with version 4 browsers, you can script the press of the Enter/Return key in any text field tosubmit a form (see Chapter 25).

Web server setup - 100Part IIJavaScript TutorialForm Controls as ObjectsThree kinds of

Thursday, July 26th, 2007

100Part IIJavaScript TutorialForm Controls as ObjectsThree kinds of HTML elements nested inside a

tag become scriptable objects in allbrowser document object models. Most of the objects owe their existence to the tagin the page s source code. Only the value assigned to the typeattribute of an tagdetermines whether the element is a text box, password entry field, hidden field, button, checkbox, or radio button. The other two kinds of form controls, textareaand select, havetheir own tags. To reference a particular form control as an object in DOM Level 0 syntax, you build thereference as a hierarchy starting with the document, through the form, and then to the con- trol. You ve already seen how many ways you can reference merely the form part all ofwhich are valid for building form control references. But if you were using only the identifiersassigned to the form and form control elements (that is, none of the associated arrays ofelements), the syntax is as follows: document.formName.controlNameFor example, consider the following simple form:

The following sample references to the text input control are all valid: document.searchForm.entrydocument.searchForm.elements[0] document.forms[ searchForm ].elements[ entry ] document.forms[ searchForm ].entryWhile form controls have several properties in common, some properties are unique to a par- ticular control type or related types. For example, only a selectobject offers a property thatreveals which item in its list is currently selected. But checkboxes and radio buttons bothhave a property that indicates whether the control is currently set to on. Similarly, all text- oriented controls operate the same way for reading and modifying their content. Having a good grasp of the scriptable features of form control objects is important to yoursuccess with JavaScript. In the next sections, you meet the most important form controlobjects and see how scripts interact with them. Text-related objectsEach of the four text-related HTML form elements inputelements of the text, password, and hidden types, plus the textareaelement is an element in the document object hierar- chy. All but the hidden object display themselves in the page, enabling users to enter infor- mation. These objects also display text information that changes in the course of using a page(although browsers capable of modern Dynamic HTML also allow the scripted change ofother body text in a document). To make these form control objects scriptable in a page, you do nothing special to their nor- mal HTML tags with the possible exception of assigning a nameattribute. I strongly recom- mend assigning unique names to every text-related form control element if your scripts willbe getting or setting properties or invoking their methods. Besides, if the form is actually sub- mitted to a server program, the nameattributes must be assigned in order for the server toreceive the element s data.

99Chapter 9Forms and Form ElementsAccessing form propertiesForms are (Web server iis)

Thursday, July 26th, 2007

99Chapter 9Forms and Form ElementsAccessing form propertiesForms are created entirely from standard HTML tags in the page. You can set attributes forname, target, action, method, and enctype. Each of these is a property of a form object, accessed by all lowercase versions of those words, as indocument.forms[0].actiondocument.formName.actionTo change any of these properties, simply assign new values to them: document.forms[0].action = http://www.giantco.com/cgi/login.pl ; form.elements[] propertyIn addition to keeping track of each type of element inside a form, the browser also maintainsa list of all control elements within a form. This list is another array, with items listed accord- ing to the order in which their HTML tags appear in the source code. It is generally more effi- cient to create references to elements directly, using their names. However, sometimes ascript needs to look through all of the elements in a form. This is especially true if the contentof a form changes with each loading of the page because the number of text fields changesbased on the user s browser type. (For example, a script on the page uses document.write() to add an extra text box for information required only from Windows users.) The following code fragment shows the form.elements[]property at work in a forrepeatloop that looks at every element in a form to set the contents of text fields to an empty string. The script cannot simply barge through the form and set every element s content to an emptystring because some elements may be types (for example, a button) whose valuepropertieshave different purposes. var form = window.document.forms[0]; for (var i = 0; i < form.elements.length; i++) { if (form.elements[i].type == text ) { form.elements[i].value = ; } } In the first statement, I create a variable form that holds a reference to the first form ofthe document. I do this so that when I make many references to form elements later in thescript, the typical length of each reference is much shorter (and marginally faster). I can usethe formvariable as a shortcut to building references to items more deeply nested in theform. Next, I start looping through the items in the elementsarray for the form. Each form elementhas a typeproperty, which reveals what kind of form control it is: text, button, radio, check- box, and so on. I m interested in finding elements whose type is text. For each of those, I setthe valueproperty to an empty string. I return to forms later in this chapter to show you how to submit a form without a Submit but- ton and how client-side form validation works.

Web design portfolio - 98Part IIJavaScript TutorialForm as object and containerUnlike the

Wednesday, July 25th, 2007

98Part IIJavaScript TutorialForm as object and containerUnlike the modern DOM s ID reference model which lets a script dive anywhere into a docu- ment to grab an element object reference DOM Level 0 form syntax imposes a hierarchicalapproach. It treats the formobject as a container whose contents consist of the form controlelement objects (input, select, and textareaelements). Figure 9-1 shows the structure ofthis hierarchy and its place relative to the documentobject. You ll see the effect this struc- ture has on the way you reference form control elements in a moment. This structure echoesperfectly the HTML tag organization within the

and

tag bookends. In addition to a large collection of properties and methods it has in common with all HTMLelement objects, the formobject features a number of items that are unique to this object. Almost all of these unique properties are scripted representations of the formelement sattributes. Scriptable browsers allow scripts to change these properties under script control, which gives your scripts potentially significant power to direct the behavior of a form sub- mission in response to user selections on the page. Figure 9-1:DOM Level 0 hierarchy for forms and controls. textradiobuttonformdocumentwindowselecttextareacheckboxpasswordsubmitresetoption

Forms and FormElementsMost interactivity between a Web page (Web site development)

Wednesday, July 25th, 2007

Forms and FormElementsMost interactivity between a Web page and the user takes placeinside a form. That s where a lot of the interactive HTML stufflives for every browser: text fields, buttons, checkboxes, option lists, and so on. As described in earlier chapters, you may use the modern DOMdocument.getElementById()method to reference any element, including forms and form controls. But this chapter focuses on anolder, yet equally valid way of referencing forms and controls. It simportant to be familiar with this widely used syntax so that you canunderstand existing JavaScript source code written according to theoriginal (and fully backward-compatible) form syntax the so-calledDOM Level 0 syntax. The form ObjectUsing the original DOM Level 0 syntax, you can reference a formobject either by its position in the array of forms contained by a doc- ument or by name (if you assign an identifier to the nameattributeinside the

tag). If only one form appears in the document, it isstill a member of an array (a one-element array) and is referenced asfollows: document.forms[0] Or use the string of the element s name as the array index: document.forms[formName] Notice that the array reference uses the plural version of the word, followed by a set of square brackets containing the index number(zero is always first) or name of the element. Alternatively, you canuse the form s name (not as a quoted string) as if it were a propertyof the documentobject: document.formName99CHAPTER …In This ChapterWhat the formobjectrepresentsHow to access keyformobject propertiesand methodsHow text, button, andselectobjects workHow to submit formsfrom a scriptHow to passinformation from formelements to functions …

95Chapter 8Window and Document ObjectsThe sole parameter of (Sri lanka web server)

Tuesday, July 24th, 2007

95Chapter 8Window and Document ObjectsThe sole parameter of this method is a quoted string containing the ID of the element youwish to reference. The method returns a value, which you typically preserve in a variable foruse by subsequent script statements: var oneTable = document.getElementById( salesResults ); After the assignment statement, the variable represents the element object, allowing you toget and set its properties or invoke whatever methods belong to that type of object. The next logical step past the document level in the object hierarchy is the form. That swhere you will spend the next lesson. Exercises1.Which of the following references are valid and which are not? Explain what is wrongwith the invalid references. a.window.document.form[0] b.self.entryForm.submit() c.document.forms[2].named.document.getElementByID( firstParagraph ) e.newWindow.document.write( Howdy ) 2.Write the JavaScript statement that displays a message in the status bar welcoming vis- itors to your Web page. 3.Write the JavaScript statement that executes while the page loads to display the samemessage from question 2 to the document as an

-level headline on the page. 4.Create a page that prompts the user for his or her name as the page loads (via a dialogbox) and then welcomes the user by name in the body of the page. 5.Create a page with any content you like, but one that automatically displays a dialogbox after the page loads to show the user the URL of the current page. …

94Part IIJavaScript TutorialListing 8-3(continued) document.createElement() anddocument.createTextNode() methodsThe document.write()method (Free web hosts)

Tuesday, July 24th, 2007

94Part IIJavaScript TutorialListing 8-3(continued)

document.createElement() anddocument.createTextNode() methodsThe document.write()method works on a piece of a Web page only while the page is load- ing into the browser the first time. Any subsequent invocation of the method erases the pageand writes a new page. But if you want to add to or modify a page that has already loaded, you need to call upon the Dynamic HTML capabilities of W3C DOM-compatible browsers. Your goal will be to add to, delete from, or replace sections of the node hierarchy of the docu- ment. Most element objects have methods to perform those actions (see more in-depth dis- cussion in Chapter 14). But if you need to add content, you ll have to create new element ortext nodes. The documentobject has the methods to do that. The document.createElement()method lets you create in the browser s memory a brandnew element object. To specify the precise element you wish to create, pass the tag name ofthe element as a string parameter of the method: var newElem = document.createElement( p ); You may also wish to add some attribute values to the element, which you may do by assign- ing values to the newly created object s properties, even before the element becomes part ofthe document. As you saw in Chapter 4 s object hierarchy illustrations, an element object frequently needstext content between its start and end tags. The W3C DOM way to create that text is to gener- ate a brand new text node via the document.createTextNode()method, and populate thenode with the desired text. For example: var newText = document.createTextNode( Greetings to all. ); The act of creating an element or text node does not, by itself, influence the document nodetree. You must invoke one of the various insertion or replacement methods (see Chapter 14) to place the new text node into its element and place the element into the document. Youlearn how to do this in the last tutorial chapter (Chapter 12). document.getElementById() methodYou met the document.getElementById() method in Chapter 4 when learning about the syntaxfor referencing element objects. This W3C DOM method is one you will use a lot. Get to knowits finger-twisting name well. Be sure to honor the upper- and lowercase spelling of this all- important method.

93Chapter 8Window and Document (Web site templates) Objects In Listing 8-3,

Monday, July 23rd, 2007

93Chapter 8Window and Document Objects

In Listing 8-3, the situation is a bit more complex because the script generates a subwindowto which is written an entirely script-generated document. To keep the reference to the newwindow alive across both functions, the newWindowvariable is declared as a global variable. As soon as the page loads, the onloadevent handler invokes the makeNewWindow()function. This function generates a blank subwindow. I added a property to the third parameter of thewindow.open()method that instructs the status bar of the subwindow to appear. A button in the page invokes the subWrite()method. The first task it performs is to checkthe closedproperty of the subwindow. This property (which exists only in newer browserversions) returns trueif the referenced window is closed. If that s the case (if the user manu- ally closed the window), the function invokes the makeNewWindow()function again to reopenthat window. With the window open, new content is assembled as a string variable. As with Listing 8-2, thecontent is written in one blast (although that isn t necessary for a separate window), followedby a close()method. But notice an important difference: both the write()and close() methods explicitly specify the subwindow. Listing 8-3:Using document.write() on Another Window