Archive for May, 2007

105Chapter 9Forms and Form ElementsThe most (1 on 1 web hosting) important property

Thursday, May 3rd, 2007

105Chapter 9Forms and Form ElementsThe most important property of the selectobject itself is the selectedIndexproperty, accessed as follows: document.form[0].selectName.selectedIndexThis value is the index number of the currently selected item. As with most index countingschemes in JavaScript, the first item (the one at the top of the list) has an index of zero. TheselectedIndexvalue is critical for enabling you to access properties of the selected option. Two important properties of an option item are textand value, accessed as follows: document.forms[0].selectName.options[n].textdocument.forms[0].selectName.options[n].valueThe textproperty is the string that appears onscreen in the selectobject. It is unusual forthis information to be exposed as a formobject property because in the HTML that generatesa selectobject, the text is defined as an

Virtual web hosting - 104Part IIJavaScript Tutorialthe onclickevent handler invokes the fullName()function.

Wednesday, May 2nd, 2007

104Part IIJavaScript Tutorialthe onclickevent handler invokes the fullName()function. In that function, the first state- ment creates a shortcut reference to the form. Next, a forrepeat loop looks through all of thebuttons in the stoogesradio button group. An ifconstruction looks at the checkedprop- erty of each button. When a button is highlighted, the breakstatement bails out of the forloop, leaving the value of the iloop counter at the number where the loop broke ranks. Thealert dialog box then uses a reference to the valueproperty of the ith button so that the fullname can be displayed in the alert. Listing 9-3:Scripting a Group of Radio Objects

Select your favorite Stooge: MoeLarryCurly

The select ObjectThe most complex form control to script is the selectelement object. As you can see fromthe DOM Level 0 form object hierarchy diagram (see Figure 9-1), the selectobject is really acompound object: an object that contains an array of optionobjects. Moreover, you canestablish this object in HTML to display itself as either a pop-up list or a scrolling list thelatter configurable to accept multiple selections by users. For the sake of simplicity at thisstage, this lesson focuses on deployment as a pop-up list that allows only single selections. Some properties belong to the entire selectobject; others belong to individual optionsinside the selectobject. If your goal is to determine which item the user selects, and youwant the code to work on the widest range of browsers, you must use properties of both theselectand optionobjects.
Note: If you are looking for cheap and reliable webhost to host and run your web application check Vision coldfusion web hosting services

103Chapter 9Forms and Form ElementsListing 9-2:The Checkbox Object s (Web hosting colocation)

Wednesday, May 2nd, 2007

103Chapter 9Forms and Form ElementsListing 9-2:The Checkbox Object s checked Property

Check here

Checkboxes are generally used as preferences setters, rather than as action inducers. While acheckbox object has an onclickevent handler, a click of a checkbox should never do any- thing drastic, such as navigate to another page. The Radio ObjectSetting up a group of radio objects for scripting requires a bit more work. To let the browsermanage the highlighting and unhighlighting of a related group of buttons, you must assign thesame name to each of the buttons in the group. You can have multiple groups within a form, but each member of the same group must share the same name. Assigning the same name to a form element forces the browser to manage the elements differ- ently than if they each had a unique name. Instead, the browser maintains an array list ofobjects with the same name. The name assigned to the group becomes the name of the array. Some properties apply to the group as a whole; other properties apply to individual buttonswithin the group and must be addressed via array index references. For example, you can findout how many buttons are in a group by reading the lengthproperty of the group: document.forms[0].groupName.lengthIf you want to find out if a particular button is currently highlighted via the same checkedproperty used for the checkbox you must access the button element individually: document.forms[0].groupName[0].checkedListing 9-3 demonstrates several aspects of the radio button object, including how to lookthrough a group of buttons to find out which one is checked and how to use the valueattribute and corresponding property for meaningful work. The page includes three radio buttons and a plain button. Each radio button s valueattribute contains the full name of one of the Three Stooges. When the user clicks the button,
Note: If you are looking for reliable webhost to maintain and run your java application check Vision java hosting services

102Part IIJavaScript TutorialListing 9-1:Getting and Setting a Text (Php web hosting)

Wednesday, May 2nd, 2007

102Part IIJavaScript TutorialListing 9-1:Getting and Setting a Text Object s value Property

Later in this chapter, I show you how to reduce even further the need for explicit referencesin functions such as upperMe()in Listing 9-1. In the meantime, notice for a moment theonsubmitevent handler in the

tag. I delve more deeply into this event handler laterin this chapter, but I want to point out the construction that prevents a single-field form frombeing submitted when you press the Enter key. If the event handler weren t there, a press ofthe Enter key would reload the page, returning the field to its original text. Try it! The Button ObjectI have used the button-type inputelement in many examples up to this point in the tutorial. The button is one of the simplest objects to script. In the simplified object model of this tuto- rial, the button object has only a few properties that are rarely accessed or modified in day- to-day scripts. Like the text object, the visual aspects of the button are governed not byHTML or scripts, but by the operating system and browser that the page visitor uses. By far, the most useful event handler of the button object is the onclickevent handler. It fires when- ever the user clicks the button. Simple enough. No magic here. The Checkbox ObjectA checkbox is also a simple element of the formobject, but some of the properties may notbe intuitive entirely. Unlike the valueproperty of a plain button object (the text of the buttonlabel), the valueproperty of a checkbox is any other text you want associated with theobject. This text does not appear on the page in any fashion, but the property (initially set viathe valueattribute) might be important to a script that wants to know more about the pur- pose of the checkbox within the form. The key property of a checkbox object is whether or not the box is checked. The checkedproperty is a Boolean value: trueif the box is checked, falseif not. When you see that aproperty is a Boolean value, it s a clue that the value might be usable in an ifor if…elsecondition expression. In Listing 9-2, the value of the checkedproperty determines which alertbox the user sees.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision shared web hosting services

Ecommerce web host - 101Chapter 9Forms and Form ElementsFor the visible objects

Wednesday, May 2nd, 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).
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision web and email hosting services

Unlimited web hosting - 100Part IIJavaScript TutorialForm Controls as ObjectsThree kinds of

Tuesday, May 1st, 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.
Note: If you are looking for high quality webhost to host and run your jsp application check Vision christian web host services

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

Tuesday, May 1st, 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.
Note: If you are looking for cheap webhost to host and run your apache application check Vision apache web hosting services

98Part IIJavaScript TutorialForm as object and (Web site translator) containerUnlike the

Tuesday, May 1st, 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
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services