Archive for May, 2007

Cedant web hosting - 115Chapter 10Strings, Math, and Datesstring.substring()method. For the second

Saturday, May 5th, 2007

115Chapter 10Strings, Math, and Datesstring.substring()method. For the second parameter, the lengthproperty of the stringprovides a basis for the ending character s index value (one more than the actual characterneeded). var stringA = The United States of America ; var excerpt = stringA.substring(stringA.indexOf( ) + 1, stringA.length); // result: excerpt = United States of America Creating statements like this one is not something you are likely to enjoy over and over again, so in Chapter 27 I show you how to create your own library of string functions you can reusein all of your scripts that need their string-handling facilities. More powerful string-matchingfacilities are built into today s browsers by way of regular expressions (see Chapter 27 andChapter 42 on the CD-ROM). The Math ObjectJavaScript provides ample facilities for math far more than most scripters who don t have abackground in computer science and math will use in a lifetime. But every genuine program- ming language needs these powers to accommodate clever programmers who can make win- dows fly in circles on the screen. The Mathobject contains all of these powers. This object is unlike most of the other objectsin JavaScript in that you don t generate copies of the object to use. Instead your scripts sum- mon a single Mathobject s properties and methods. (One Mathobject actually occurs perwindow or frame, but this has no impact whatsoever on your scripts.) Programmers call thiskind of fixed object a staticobject. That Mathobject (with an uppercase M) is part of the refer- ence to the property or method. Properties of the Mathobject are constant values, such as piand the square root of two: var piValue = Math.PI; var rootOfTwo = Math.SQRT2; Mathobject methods cover a wide range of trigonometric functions and other math functionsthat work on numeric values already defined in your script. For example, you can find whichof two numbers is the larger: var larger = Math.max(value1, value2); Or you can raise one number to a power of 10: var result = Math.pow(value1, 10); More common, perhaps, is the method that rounds a value to the nearest integer value: var result = Math.round(value1); Another common request of the Mathobject is a random number. The Math.random() method returns a floating-point number between 0 and 1. If you design a script to act like acard game, you need random integers between 1 and 52; for dice, the range is 1 to 6 per die. To generate a random integer between zero and any top value, use the following formula: Math.floor(Math.random() * (n + 1)) where nis the top number. (Math.floorreturns the integer part of any floating-point num- ber.) To generate random numbers between 1 and any higher number, use this formula: Math.floor(Math.random() * n) + 1
Note: In case you are looking for affordable webhost to host and run your web application check Vision cheap hosting services

Free web hosts - 114Part IIJavaScript TutorialThe string.indexOf()method returns a number indicating

Saturday, May 5th, 2007

114Part IIJavaScript TutorialThe string.indexOf()method returns a number indicating the index value (zero based) ofthe character in the larger string where the smaller string begins. The key point about thismethod is that if no match occurs, the returned value is -1. To find out whether the smallerstring is inside, all you need to test is whether the returned value is something other than -1. Two strings are involved with this method: the shorter one and the longer one. The longerstring is the one that appears in the reference to the left of the method name; the shorterstring is inserted as a parameter to the indexOf()method. To demonstrate the method inaction, the following fragment looks to see if the user is running Windows: var isWindows = false; if (navigator.userAgent.indexOf( Win ) != -1) { isWindows = true; } The operator in the ifconstruction s condition (!=) is the inequality operator. You can readit as meaning is not equal to. Extracting copies of characters and substringsTo extract a single character at a known position within a string, use the charAt()method. The parameter of the method is an index number (zero based) of the character to extract. When I say extract, I don t mean delete, but rather grab a snapshot of the character. The origi- nal string is not modified in any way. For example, consider a script in a main window that is capable of inspecting a variable, stringA, in another window that displays map images of different corporate buildings. Whenthe window has a map of Building C in it, the stringAvariable contains Building C. Thebuilding letter is always at the tenth character position of the string (or number 9 in a zero- based counting world), so the script can examine that one character to identify the map cur- rently in that other window: var stringA = Building C ; var bldgLetter = stringA.charAt(9); // result: bldgLetter = C Another method string.substring() enables you to extract a contiguous sequence ofcharacters, provided you know the starting and ending positions of the substring of whichyou want to grab a copy. Importantly, the character at the ending position value is not part ofthe extraction: All applicable characters, up to but not including that character, are part ofthe extraction. The string from which the extraction is made appears to the left of the methodname in the reference. Two parameters specify the starting and ending index values (zerobased) for the start and end positions: var stringA = banana daiquiri ; var excerpt = stringA.substring(2,6); // result: excerpt = nana String manipulation in JavaScript is fairly cumbersome compared to some other scriptinglanguages. Higher-level notions of words, sentences, or paragraphs are completely absent. Therefore, sometimes it takes a bit of scripting with string methods to accomplish whatseems like a simple goal. And yet you can put your knowledge of expression evaluation tothetest as you assemble expressions that utilize heavily nested constructions. For example, the following fragment needs to create a new string that consists of everything from thelarger string except the first word. Assuming the first word of other strings can be of anylength, thesecond statement utilizes the string.indexOf()method to look for the firstspace character and adds 1 to that value to serve as the starting index value for an outer
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision mysql5 web hosting services

113Chapter 10Strings, Math, and DatesYou can also (Web hosting service) combine

Saturday, May 5th, 2007

113Chapter 10Strings, Math, and DatesYou can also combine the operators if the need arises: var msg = Four score ; msg += and seven + years ago ; I use the add-by-value operator a lot when accumulating HTML text to be written to the cur- rent document or another window. String methodsOf all the core JavaScript objects, the Stringobject has the most diverse collection of meth- ods associated with it. Many methods are designed to help scripts extract segments of astring. Another group, rarely used and now obsolete in favor of CSS, wraps a string with oneof several style-oriented tags (a scripted equivalent of tags for font size, style, and the like). To use a string method, the string being acted upon becomes part of the reference followedby the method name. All methods return a value of some kind. Most of the time, the returnedvalue is a converted version of the string object referred to in the method call but the origi- nal string is still intact. To capture the modified version, you need to assign the results of themethod to a variable: var result = string.methodName(); The following sections introduce you to several important string methods available to allbrowser brands and versions. Changing string caseTwo methods convert a string to all uppercase or lowercase letters: var result = string.toUpperCase(); var result = string.toLowerCase(); Not surprisingly, you must observe the case of each letter of the method names if you wantthem to work. These methods come in handy when your scripts need to compare strings thatmay not have the same case (for example, a string in a lookup table compared with a stringtyped by a user). Because the methods don t change the original strings attached to theexpressions, you can simply compare the evaluated results of the methods: var foundMatch = false; if (stringA.toUpperCase() == stringB.toUpperCase()) { foundMatch = true; } String searchesYou can use the string.indexOf()method to determine if one string is contained byanother. Even within JavaScript s own object data, this can be useful information. For exam- ple, the navigator.userAgentproperty reveals a lot about the browser that loads the page. A script can investigate the value of that property for the existence of, say, Win to deter- mine that the user has a Windows operating system. That short string might be buried some- where inside a long string, and all the script needs to know is whether the short string ispresent in the longer one wherever it might be.
Note: If you are looking for cheap webhost to host and run your apache application check Vision jboss web hosting services

Photo web hosting - 112Part IIJavaScript Tutorialanother, as often happens in event

Saturday, May 5th, 2007

112Part IIJavaScript Tutorialanother, as often happens in event handlers. In the following example, the alert()methodrequires a quoted string as a parameter, but the entire method call also must be insidequotes: onclick= alert( Hello, all ) JavaScript imposes no practical limit on the number of characters that a string can hold. However, most older browsers have a limit of 255 characters in length for a script statement. This limit is sometimes exceeded when a script includes a lengthy string that is to becomescripted content in a page. You need to divide such lines into smaller chunks using tech- niques described in a moment. You have two ways to assign a string value to a variable. The simplest is a basic assignmentstatement: var myString = Howdy ; This works perfectly well except in some exceedingly rare instances. Beginning withNavigator 3 and Internet Explorer 4, you can also create a string object using the more formalsyntax that involves the newkeyword and a constructor function (that is, it constructs anew object): var myString = new String( Howdy ); Whichever way you use to initialize a variable with a string, the variable receiving the assign- ment can respond to all Stringobject methods. Joining stringsBringing two strings together as a single string is called concatenatingstrings, a term youlearned in Chapter 6. String concatenation requires one of two JavaScript operators. Even inyour first script in Chapter 3, you saw how the addition operator (+) linked multiple stringstogether to produce the text dynamically written to the loading Web page: document.write( of + navigator.appName + . ); As valuable as that operator is, another operator can be even more scripter friendly. Thisoperator is helpful when you are assembling large strings in a single variable. The strings maybe so long or cumbersome that you need to divide the building process into multiple state- ments. The pieces may be combinations of string literals(strings inside quotes) or variablevalues. The clumsy way to do it (perfectly doable in JavaScript) is to use the addition opera- tor to append more text to the existing chunk: var msg = Four score ; msg = msg + and seven ; msg = msg + years ago, ; But another operator, called the add-by-value operator, offers a handy shortcut. The symbolfor the operator is a plus and equal sign together (+=). This operator means append the stuffon the right of me to the end of the stuff on the left of me. Therefore, the preceding sequenceis shortened as follows: var msg = Four score ; msg += and seven ; msg += years ago, ;
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision mysql5 web hosting services

Strings, Math, andDatesFor most (Web hosting services) of the lessons in

Friday, May 4th, 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 …
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision shared web hosting services

110Part IIJavaScript TutorialExercises1.Rework Listings 9-1, 9-2, (My web site) 9-3, and

Friday, May 4th, 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. …
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

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

Friday, May 4th, 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.
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision mysql hosting services

108Part IIJavaScript TutorialListing 9-5(continued) Choose your favorite Beatle: (Best web hosting site)

Thursday, May 3rd, 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.
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision php5 hosting services

107Chapter 9Forms and Form ElementsFor other functions, you (Web hosting bandwidth)

Thursday, May 3rd, 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
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision best web hosting services

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

Thursday, May 3rd, 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
Note: If you are looking for cheap and reliable webhost to host and run your mysql application check Vision professional web hosting services