Archive for July, 2007

79Chapter 7Programming Fundamentals, Part IIIf a Web page (Post office web site)

Thursday, July 19th, 2007

79Chapter 7Programming Fundamentals, Part IIIf a Web page included these data tables and a way for a user to look up the entry date for agiven state, the page would need a way to look through all of the USStatesentries to find theindex value of the one that matches the user s entry. Then, that index value could be appliedto the stateEnteredarray to find the matching year. For this demo, the page includes a text entry field in which the user types the name of thestate to look up. In a real application, this methodology is fraught with peril unless the scriptperforms some error checking in case the user makes a mistake. But for now, I assume thatthe user always types a valid state name. (Don t ever make this assumption in your Web site spages.) An event handler from either the text field or a clickable button calls a function thatlooks up the state name, fetches the corresponding entry year, and displays an alert messagewith the information. The function is as follows: function getStateDate() { var selectedState = document.getElementById( entry ).value; for ( var i = 0; i < USStates.length; i++) { if (USStates[i] == selectedState) { break; } } alert( That state entered the Union in + stateEntered[i] + . ); } In the first statement of the function, I grab the value of the text box and assign the value to avariable, selectedState. This is mostly for convenience because I can use the shorter vari- able name later in the script. In fact, the usage of that value is inside a forloop, so the scriptis marginally more efficient because the browser doesn t have to evaluate that long referenceto the text field each time through the loop. The key to this function is in the forloop. Here is where I combine the natural behavior ofincrementing a loop counter with the index values assigned to the two arrays. Specificationsfor the loop indicate that the counter variable, i, is initialized with a value of zero. The loop isdirected to continue as long as the value of iis less than the length of the USStatesarray. Remember that the length of an array is always one more than the index value of the lastitem. Therefore, the last time the loop runs is when iis 50, which is both less than the lengthof 51 and equal to the index value of the last element. Each time after the loop runs, thecounter increments by one. Nested inside the forloop is an ifconstruction. The condition tests the value of an elementof the array against the value typed in by the user. Each time through the loop, the conditiontests a different row of the array starting with row zero. In other words, this ifconstructioncan be performed dozens of times before a match is found, but each time the value of iis onelarger than the previous try. The equality comparison operator (==) is strict when it comes to comparing string values. Such comparisons respect the case of each letter. In our example, the user must type thestate name exactly as it is stored in the USStatesarray for the match to be found. In Chapter10, you learn about some helper methods that eliminate case and sensitivity in stringcomparisons. When a match is found, the statement nested inside the ifconstruction runs. The breakstatement is designed to help control structures bail out if the program needs it. For thisapplication, it is imperative that the forloop stop running when a match for the state name

78Part IIJavaScript Tutorialcollections (Web design rates) is small enough not to

Thursday, July 19th, 2007

78Part IIJavaScript Tutorialcollections is small enough not to severely impact page loading even for dial-up users at28.8 Kbps. In Chapter 30, you also see some syntax shortcuts for creating arrays that reducesource code character counts. Accessing array dataThe array index is the key to accessing an array element. The name of the array and an indexin square brackets evaluates to the content of that array location. For example, after theUSStatesarray is built, a script can display an alert with Alaska s name in it with the follow- ing statement: alert( The largest state is + USStates[1] + . ); Just as you can retrieve data from an indexed array element, so can you change the elementby reassigning a new value to any indexed element in the array. Parallel arraysNow I show you why the numeric index methodology works well in JavaScript. To help withthe demonstration, I generate another array that is parallel with the USStatesarray. Thisnew array is also 51 elements long, and it contains the year in which the state in the corre- sponding row of USStatesentered the Union. That array construction looks like thefollowing: var stateEntered = new Array(51); stateEntered [0] = 1819; stateEntered [1] = 1959; stateEntered [2] = 1912; stateEntered [3] = 1836; … stateEntered [50] = 1890; In the browser s memory, then, are two data tables that you can visualize as looking like themodel in Figure 7-1. I can build more arrays that are parallel to these for items such as thepostal abbreviation and capital city. The important point is that the zeroth element in each ofthese tables applies to Alabama, the first state in the USStatesarray. Figure 7-1:Visualization of two related parallel data tables. “Alabama” “Alaska” “Arizona” “Arkansas” “Wyoming” 18191959191218361890[0] [1] [2] [3] [50] stateEnteredUSStates…. …. ….

77Chapter 7Programming Fundamentals, Part IIitem in an array, (Web design course)

Wednesday, July 18th, 2007

77Chapter 7Programming Fundamentals, Part IIitem in an array, you need to know the name of the array and the index for the row. Becauseindex values start with zero, the total number of items of the array (as determined by thearray s lengthproperty) is always one more than the highest index value of the array. More advanced array concepts enable you to create the equivalent of an array with multiple columns (described in Chapter 30). For this tutorial, I stay with the single- column basic array. Data elements inside JavaScript arrays can be any data type, including objects. And, unlike alot of other programming languages, different rows of the same JavaScript array can containdifferent data types. Creating an arrayAn array is stored in a variable, so when you create an array you assign the new array objectto the variable. (Yes, arrays are objects, but they belong to the core JavaScript languagerather than the document object model.) A special keyword new preceding a call to theJavaScript function that generates arrays creates space in memory for the array. An optionalparameter to the Array()function enables you to specify at the time of creation how manyelements (rows) of data eventually will occupy the array. JavaScript is very forgiving aboutthis because you can change the size of an array at any time. Therefore, if you omit a parame- ter when generating a new array, your script incurs no penalty. To demonstrate the array creation process, I create an array that holds the names of the50states plus the District of Columbia (a total of 51). The first task is to create that arrayandassign it to a variable of any name that helps me remember what this collection of dataisabout: var USStates = new Array(51); At this point, the USStatesarray is sitting in memory like a 51-row table with no data in it. Tofill the rows, I must assign data to each row. Addressing each row of an array requires a spe- cial way of indicating the index value of the row: square brackets after the name of the array. The first row of the USStatesarray is addressed asUSStates[0] To assign the string name of the first state of the alphabet to that row, I use a simple assign- ment operator: USStates[0] = Alabama ; To fill in the rest of the rows, I include a statement for each row: USStates[1] = Alaska ; USStates[2] = Arizona ; USStates[3] = Arkansas ; … USStates[50] = Wyoming ; Therefore, if you want to include a table of information in a document from which a scriptcanlook up information without accessing the server, you include the data in the documentin the form of an array creation sequence. When the statements run as the document loads, by the time the document finishes loading into the browser, the data collection array is builtand ready to go. Despite what appears to be the potential for a lot of statements in a docu- ment for such a data collection, the amount of data that must download for typical array

Sri lanka web server - 76Part IIJavaScript Tutorialnot overridden by a local is

Wednesday, July 18th, 2007

76Part IIJavaScript Tutorialnot overridden by a local is available for use inside the function. The expression is accumu- lating HTML to be written to the page, so it ends with a period and a
tag. The final state- ment of the function writes the content to the page. After the function completes its task, the next statement in the Body script writes anotherstring to the page. Because this script statement is executing in global space (that is, notinside any function), it accesses only global variables including those defined in another When the page loads, the script in the Head portion initializes the two global variables (aBoyand hisDog) and defines the demo()function in memory. In the Body, another script beginsby invoking the function. Inside the function, a local variable is initialized with the same nameas one of the global variables hisDog. In JavaScript, such a local initialization overrides theglobal variable for all statements inside the function. (But note that if the varkeyword is leftoff of the local initialization, the statement reassigns the value of the global version to Gromit. ) Another local variable, output, is merely a repository for accumulating the text that is to bewritten to the screen. The accumulation begins by evaluating the local version of the hisDogvariable. Then it concatenates some hard-wired text (note the extra spaces at the edges ofthe string segment). Next comes the evaluated value of the aBoyglobal variable any global

Web server - 74Part IIJavaScript TutorialParameters (also known as arguments) provide

Wednesday, July 18th, 2007

74Part IIJavaScript TutorialParameters (also known as arguments) provide a mechanism for handing off a value fromone statement to another by way of a function call. If no parameters occur in the function def- inition, both the function definition and call to the function have only empty sets of parenthe- ses (as shown in Chapter 5, Listing 5-8). When a function receives parameters, it assigns the incoming values to the variable namesspecified in the function definition s parentheses. Consider the following script segment: function sayHiToFirst(a, b, c) { alert( Say hello, + a); } sayHiToFirst( Gracie , George , Harry ); sayHiToFirst( Larry , Moe , Curly ); After the function is defined in the script, the next statement calls that very function, passingthree strings as parameters. The function definition automatically assigns the strings to vari- ables a, b, and c. Therefore, before the alert()statement inside the function ever runs, aevaluates to Gracie, bevaluates to George, and cevaluates to Harry. In the alert() statement, only the avalue is used and the alert readsSay hello, GracieWhen the user closes the first alert, the next call to the function occurs. This time through, different values are passed to the function and assigned to a, b, and c. The alert dialog boxreadsSay hello, LarryUnlike other variables that you define in your script, function parameters do not use the varkeyword to initialize them. They are automatically initialized whenever the function is called. Variable scopeSpeaking of variables, it s time to distinguish between variables that are defined outside andthose defined inside of functions. Variables defined outside of functions are called global vari- ables; those defined inside functions with the varkeyword are called local variables. A global variable has a slightly different connotation in JavaScript than it has in most otherlanguages. For a JavaScript script, the globe of a global variable is the current documentloaded in a browser window or frame. Therefore, when you initialize a variable as a globalvariable, it means that all script statements in the page (including those inside functions) have direct access to that variable value. Statements can retrieve and modify global variablesfrom anywhere in the page. In programming terminology, this kind of variable is said to haveglobal scopebecause everything on the page can see it. It is important to remember that the instant a page unloads itself, all global variables definedin that page disappear from memory forever. If you need a value to persist from one page toanother, you must use other techniques to store that value (for example, as a global variablein a framesetting document, as described in Chapter 16; or in a cookie, as described inChapter 18). While the varkeyword is usually optional for initializing global variables, Istrongly recommend you use it for all variable initializations to guard against future changesto the JavaScript language. In contrast to the global variable, a local variable is defined inside a function. You already sawhow parameter variables are defined inside functions (without varkeyword initializations). But you can also define other variables with the varkeyword (absolutely required for local

73Chapter 7Programming Fundamentals, Part IIclassification of routine exists (Yahoo web hosting)

Tuesday, July 17th, 2007

73Chapter 7Programming Fundamentals, Part IIclassification of routine exists for JavaScript. A function is capable of returning a value to thestatement that invoked it, but this is not a requirement. However, when a function doesreturn a value, the calling statement treats the function call like any expression plugging inthe returned value right where the function call is made. I will show some examples in amoment. Formal syntax for a function is as follows: function functionName( [parameter1]…[,parameterN] ) { statement[s] } Names you assign to functions have the same restrictions as names you assign to HTML ele- ments and variables. You should devise a name that succinctly describes what the functiondoes. I tend to use multiword names with the interCap (internally capitalized) format thatstart with a verb because functions are action items, even if they do nothing more than get orset a value. Another practice to keep in mind as you start to create functions is to keep the focus of eachfunction as narrow as possible. It is possible to generate functions that are literally hundredsof lines long. Such functions are usually difficult to maintain and debug. Chances are that youcan divide the long function into smaller, more tightly focused segments. Function parametersIn Chapter 5, you saw how an event handler invokes a function by calling the function byname. Any call to a function, including one that comes from another JavaScript statement, works the same way: a set of parentheses follows the function name. You also can define functions so they receive parameter values from the calling statement. Listing 7-1 shows a simple document that has a button whose onclickevent handler calls afunction while passing text data to the function. The text string in the event handler call is ina nested string a set of single quotes inside the double quotes required for the entire eventhandler attribute. Listing 7-1:Calling a Function from an Event Handler

72Part IIJavaScript TutorialA repeat looplets a script cycle (Free php web host)

Tuesday, July 17th, 2007

72Part IIJavaScript TutorialA repeat looplets a script cycle through a sequence of statements until some condition ismet. For example, a JavaScript data validation routine might inspect every character that youenter into a form text field to make sure that each one is a number. Or if you have a collectionof data stored in a list, the loop can check whether an entered value is in that list. Once thatcondition is met, the script can then break out of the loop and continue with the next state- ment after the loop construction. The most common repeat loop construction used in JavaScript is called the forloop. It getsits name from the keyword that begins the construction. A forloop is a powerful devicebecause you can set it up to keep track of the number of times the loop repeats itself. The for- mal syntax of the forloop is as follows: for ([initial expression]; [condition]; [update expression]) { statement[s] inside loop} The square brackets mean that the item is optional. However, until you get to know the forloop better, I recommend designing your loops to utilize all three items inside the parenthe- ses. The initial expressionportion usually sets the starting value of a counter variable. Thecondition the same kind of condition you saw for ifconstructions defines the conditionthat forces the loop to stop going around and around. Finally, the update expressionis a state- ment that executes each time all of the statements nested inside the construction completerunning. A common implementation initializes a counting variable, i, increments the value of iby oneeach time through the loop, and repeats the loop until the value of iexceeds some maximumvalue, as in the following: for (var i = startValue; i <= maxValue; i++) { statement[s] inside loop} Placeholders startValueand maxValuerepresent any numeric values, including explicitnumbers or variables holding numbers. In the update expression is an operator you have notseen yet. The ++operator adds 1 to the value of ieach time the update expression runs atthe end of the loop. If startValueis 1, the value of iis 1 the first time through the loop, 2the second time through, and so on. Therefore, if maxValueis 10, the loop repeats itself 10times (in other words, as long as iis less than or equal to 10). Generally speaking, the state- ments inside the loop use the value of the counting variable in their execution. Later in thislesson, I show how the variable can play a key role in the statements inside a loop. At thesame time, you will see how to break out of a loop prematurely and why you may need to dothis in a script. FunctionsIn Chapter 5, you saw a preview of the JavaScript function. A functionis a definition of a set ofdeferred actions. Functions are invoked by event handlers or by statements elsewhere in thescript. Whenever possible, good functions are designed for reuse in other documents. Theycan become building blocks you use over and over again. If you have programmed before, you can see parallels between JavaScript functions and otherlanguages subroutines. But unlike some languages that distinguish between procedures(which carry out actions) and functions (which carry out actions and return values), only one

71Chapter 7Programming Fundamentals, Part IIIn (Yahoo free web hosting) this example, the

Tuesday, July 17th, 2007

71Chapter 7Programming Fundamentals, Part IIIn this example, the data type of the value inside myAgemust be a number so that the propercomparison (via the

70Part IIJavaScript TutorialIn your trip to the store, (Abyss web server)

Monday, July 16th, 2007

70Part IIJavaScript TutorialIn your trip to the store, you go through the same kinds of decisions and repetitions that yourJavaScript programs also encounter. If you understand these frameworks in real life, you cannow look into the JavaScript equivalents and the syntax required to make them work. Control StructuresIn the vernacular of programming, the kinds of statements that make decisions and looparound to repeat themselves are called control structures. A control structure directs the exe- cution flow through a sequence of script statements based on simple decisions and otherfactors. An important part of a control structure is the condition. Just as you may travel differentroutes to work depending on certain conditions (for example, nice weather, nighttime, attend- ing a soccer game), so, too, does a program sometimes have to branch to an execution routeif a certain condition exists. Each condition is an expression that evaluates to trueorfalse one of those Boolean data types mentioned in Chapter 6. The kinds of expressionscommonly used for conditions are expressions that include a comparison operator. You dothe same in real life: If it is true that the outdoor temperature is less than freezing, you put ona coat before going outside. In programming, however, the comparisons are strictly compar- isons of values. JavaScript provides several kinds of control structures for different programming situations. Three of the most common control structures you ll use are ifconstructions, if…elseconstructions, and forloops. Chapter 31 covers in great detail other common control structures you should know. For thistutorial, however, you need to learn about the three common ones just mentioned. if constructionsThe simplest program decision is to follow a special branch or path of the program if a cer- tain condition is true. Formal syntax for this construction follows. Items in italics get replacedin a real script with expressions and statements that fit the situation. if (condition) { statement[s] if true} Don t worry about the curly braces yet. Instead, get a feel for the basic structure. The key- word, if, is a must. In the parentheses goes an expression that evaluates to a Boolean value. This is the condition being tested as the program runs past this point. If the condition evalu- ates to true, one or more statements inside the curly braces execute before continuing onwith the next statement after the closing brace. If the condition evaluates to false, the state- ments inside the curly braces are ignored and processing continues with the next statementafter the closing brace. The following example assumes that a variable, myAge, has had its value set earlier in thescript (exactly how is not important for this example). The condition expression comparesthe value myAgeagainst a numeric value of 18. if (myAge < 18) { alert( Sorry, you cannot vote. ); }