Archive for July, 2007

Web hosting provider - Strings, Math, andDatesFor most of the lessons in

Tuesday, July 31st, 2007

Strings, Math, andDatesFor most of the lessons in the tutorial so far, the objects at the cen- ter of attention belong to the document object model. But as indi- cated in Chapter 2, a clear dividing line exists between the documentobject model and the JavaScript language. The language has some ofits own objects that are independent of the document object model. These objects are defined such that if a vendor wished to implementJavaScript as the programming language for an entirely different kindof product, the language would still use these core facilities for han- dling text, advanced math (beyond simple arithmetic), and dates. You can find formal specifications of these objects in the ECMA-262recommendation. Core Language ObjectsIt is often difficult for newcomers to programming or even experi- enced programmers who have not worked in object-oriented worldsbefore to think about objects, especially when attributed to things that don t seem to have a physical presence. For example, itdoesn t require lengthy study to grasp the notion that a button on apage is an object. It has several physical properties that make perfectsense. But what about a string of characters? As you learn in thischapter, in an object-based environment such as JavaScript, every- thing that moves is treated as an object each piece of data from aBoolean value to a date. Each such object probably has one or moreproperties that help define the content; such an object may also havemethods associated with it to define what the object can do or whatyou can do to the object. I call all objects that are not part of the document object model corelanguage objects. You can see the full complement of them in theQuick Reference in Appendix A. In this chapter, I focus on the String, Math, and Dateobjects. String ObjectsYou have already used Stringobjects many times in earlier lessons. A stringis any text inside a quote pair. A quote pair consists of eitherdouble quotes or single quotes. This allows one string to nest inside1010CHAPTER …In This ChapterHow to modify stringswith common stringmethodsWhen and how to usethe MathobjectHow to use the Dateobject …

110Part IIJavaScript TutorialExercises1.Rework Listings 9-1, 9-2, 9-3, and (Web server version)

Tuesday, July 31st, 2007

110Part IIJavaScript TutorialExercises1.Rework Listings 9-1, 9-2, 9-3, and 9-4 so that the script functions all receive the mostefficient form or form element references directly from the invoking event handler. 2.For the following form (assume it s the only form on the page), write at least 10 ways toreference the text input field as an object in all modern scriptable browsers.

3.In the following HTML tag, what kind of information do you think is being passed withthe event handler? Write a function that displays in an alert dialog box the informationbeing passed. 4.A document contains two forms named specificationsand accessories. In theaccessoriesform is a field named acc1. Write at least two different statements thatset the contents of that field to Leather Carrying Case. 5.Create a page that includes a selectobject to change the background color of the cur- rent page. The property that you need to set is document.bgColor, and the three val- ues you should offer as options are red, yellow, and green. In the selectobject, thecolors should display as Stop, Caution, and Go. …

109Chapter 9Forms and Form ElementsListing 9-6 shows a (Professional web hosting)

Monday, July 30th, 2007

109Chapter 9Forms and Form ElementsListing 9-6 shows a page with a simple validation routine that ensures all fields have some- thing in them before allowing submission to continue. (The sample form has no actionattribute, so this sample form doesn t get sent to the server.) Notice how the onsubmiteventhandler (which passes a reference to the formobject as a parameter in this case the thiskeyword points to the formobject because its tag holds the event handler) includes thereturnkeyword before the function name. When the function returns its trueor falsevalue, the event handler evaluates to the requisite returntrueor returnfalse. Listing 9-6:Last-Minute Checking Before Form Submission

Please enter all requested information:
First Name:
Last Name:
Rank:
Serial Number:

One quirky bit of behavior involving the submit()method and onsubmitevent handlerneeds explanation. While you might think (and logically so, in my opinion) that the submit() method would be the exact scripted equivalent of a click of a real Submit button, it s not. Thesubmit()method does not cause the form s onsubmitevent handler to fire at all. If you wantto perform validation on a form submitted via the submit()method, invoke the validation inthe script function that ultimately calls the submit()method. So much for the basics of forms and form controls. In the next chapter, you step away fromHTML for a moment to look at more advanced JavaScript core language items: strings, math, and dates.

108Part IIJavaScript TutorialListing 9-5(continued) Choose your favorite Beatle:

Monday, July 30th, 2007

108Part IIJavaScript TutorialListing 9-5(continued)

Choose your favorite Beatle: JohnPaulGeorgeRingo

Enter the name of your favorite Beatles song:

Get to know the usage of the thiskeyword in passing formand form elementobjects tofunctions. The technique not only saves you typing in your code, but it also ensures accuracyin references to those objects. Submitting and Prevalidating FormsThe scripted equivalent of submitting a form is the formobject s submit()method. All youneed in the statement is a reference to the form and this method: document.forms[0].submit(); Before you get ideas about having a script silently submit a form to a URL bearing themailto:protocol, forget it. Because such a scheme could expose visitors e-mail addresseswithout their knowledge, mailto:submissions are either blocked or revealed to users as asecurity precaution. Before a form is submitted, you may wish to perform some last-second validation of data inthe form or in other scripting (for example, changing the form s actionproperty based onuser choices). You can do this in a function invoked by the form s onsubmitevent handler. Specific validation routines are beyond the scope of this tutorial (but are explained in sub- stantial detail in Chapter 43 on the CD-ROM), but I want to show you how the onsubmiteventhandler works. You can let the results of a validation function cancel a submission if the validation showssome incorrect data or empty fields. To control submission, the onsubmitevent handlermust evaluate to returntrue(to allow submission to continue) or returnfalse(to cancelsubmission). This is a bit tricky at first because it involves more than just having the functioncalled by the event handler return trueor false. The returnkeyword must be part of thefinal evaluation.

Web hosting compare - 107Chapter 9Forms and Form ElementsFor other functions, you

Sunday, July 29th, 2007

107Chapter 9Forms and Form ElementsFor other functions, you may wish to receive a reference to the entire form, rather than justthe object calling the function. This is certainly true if the function needs to access other ele- ments of the same form. Because every form control object contains a property that points tothe containing form, you can use the thiskeyword to reference the current control, plus itsformproperty as this.form, as in The function definition should then have a parameter variable ready to be assigned to theform object reference. Again, you decide the name of the variable. I tend to use the variablename formas a way to remind me exactly what kind of object is referenced. function inspect(form) { statement[s] } Listing 9-5 demonstrates passing both an individual form element and the entire form in theperformance of two separate acts. This page makes believe it is connected to a database ofBeatles songs. When you click the Process Data button, it passes the formobject, which theprocessData()function uses to access the group of radio buttons inside a forloop. Additional references using the passed formobject extract the valueproperties of theselected radio button and the text field. The text field has its own event handler, which passes just the text field to the verifySong() function. Notice how short the reference is to reach the valueproperty of the song fieldinside the function. Listing 9-5:Passing a Form Object and Form Element to Functions Continued

106Part IIJavaScript TutorialListing 9-4(continued) Choose a place to

Sunday, July 29th, 2007

106Part IIJavaScript TutorialListing 9-4(continued)

Choose a place to go:

Recent browsers also expose the valueproperty of the selected option item by way of thevalueproperty of the selectobject. This is certainly a logical and convenient shortcut, andyou can use it safely if your target browsers include IE, Mozilla-based browsers, and Safari. There is much more to the selectobject, including the ability to change the contents of a listin newer browsers. Chapter 24 covers the selectobject in depth. Passing Form Data and Elements to FunctionsIn all of the examples so far in this lesson, when an event handler invokes a function thatworks with form elements, the form or form control is explicitly referenced in the function. But valuable shortcuts exist for transferring information about the form or form controldirectly to the function without dealing with those typically long references that start withthe windowor documentobject level. JavaScript features a keyword this that always refers to whatever object contains thescript in which the keyword is used. Thus, in an onchangeevent handler for a text field, youcan pass a reference to the text object to the function by inserting the thiskeyword as aparameter to the function: At the receiving end, the function defines a parameter variable that turns that reference into avariable that the rest of the function can use: function upperMe(field) { statement[s] } The name you assign to the function s parameter variable is purely arbitrary, but it is helpfulto give it a name that expresses what the reference is. Importantly, this reference is a live connection back to the object. Therefore, statements in the script can get and set propertyvalues of the object at will. Note

Web space - 105Chapter 9Forms and Form ElementsThe most important property

Saturday, July 28th, 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

104Part IIJavaScript Tutorialthe onclickevent handler invokes the fullName()function. (Web hosting bandwidth)

Saturday, July 28th, 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.

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

Friday, July 27th, 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,

102Part IIJavaScript TutorialListing 9-1:Getting and Setting a Text (Web design seattle)

Friday, July 27th, 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.