Archive for April, 2007

Web hosting provider - 65Chapter 6Programming Fundamentals, Part IBut as the 6

Sunday, April 22nd, 2007

65Chapter 6Programming Fundamentals, Part IBut as the 6 is about to be added to the 3, JavaScript lets the string-ness of the 3 rule. The 6 is converted to a string, and two string values are joined to yield 63. Most of your concern about data types will focus on performing math operations like theones here. However, some object methods also require one or more parameters of particulardata types. While JavaScript provides numerous ways to convert data from one type toanother, it is appropriate at this stage of the tutorial to introduce you to the two most com- mon data conversions: string to number and number to string. Converting strings to numbersAs you saw in the last section, if a numeric value is stored as a string as it is when enteredinto a form text field your scripts may have difficulty applying that value to a math opera- tion. The JavaScript language provides two built-in functions to convert string representa- tions of numbers to true numbers: parseInt()and parseFloat(). There is a difference between integers and floating-point numbers in JavaScript. Integersarealways whole numbers, with no decimal point or numbers to the right of a decimal. Floating- point numbers, on the other hand, have fractional values to the right of the decimal. By andlarge, JavaScript math operations don t differentiate between integers and floating-point num- bers: A number is a number. The only time you need to be cognizant of the difference is whena method parameter requires an integer because it can t handle fractional values. For exam- ple, parameters to the scroll()method of a window require integer values of the number ofpixels vertically and horizontally you want to scroll the window. That s because you can tscroll a window a fraction of a pixel on the screen. To use either of these conversion functions, insert the string value you wish to convert as aparameter to the function. For example, look at the results of two different string values whenpassed through the parseInt()function: parseInt( 42 ) // result = 42parseInt( 42.33 ) // result = 42Even though the second expression passes the string version of a floating-point number tothe function, the value returned by the function is an integer. No rounding of the value occurshere (although other math functions can help with that if necessary). The decimal and every- thing to its right are simply stripped off. The parseFloat()function returns an integer if it can; otherwise, it returns a floating-pointnumber as follows: parseFloat( 42 ) // result = 42parseFloat( 42.33 ) // result = 42.33Because these two conversion functions evaluate to their results, you simply insert the entirefunction wherever you need a string value converted to a number. Therefore, modifying anearlier example in which one of three values was a string, the complete expression can evalu- ate to the desired result: 3 + 3 + parseInt( 3 ) // result = 9Converting numbers to stringsYou ll have less need for converting a number to its string equivalent than the other wayaround. As you saw in the previous section, JavaScript gravitates toward strings when faced
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

64Part IIJavaScript TutorialThe plus symbol is one of (Web server info)

Sunday, April 22nd, 2007

64Part IIJavaScript TutorialThe plus symbol is one of JavaScript s ways of joining strings. Before JavaScript can displaythis line, it must perform some quick evaluations. The first evaluation is the value of thenavigator.appNameproperty. This property evaluates to a string of the name of yourbrowser. With that expression safely evaluated to a string, JavaScript can finish the job ofjoining the three strings in the final evaluation. The evaluated string expression is what ulti- mately appears on the Web page. Expressions and variablesAs one more demonstration of the flexibility that expression evaluation offers, this sectionshows you a slightly different route to the document.write()statement. Rather than jointhose strings as the direct parameter to the document.write()method, I can gather thestrings in a variable and then apply the variable to the document.write()method. Here show that sequence looks, as I simultaneously declare a new variable and assign it a value: var textToWrite = of + navigator.appName + . ; document.write(textToWrite); This method works because the variable, textToWrite, evaluates to the combined string. Thedocument.write()method accepts that string value and does its display job. As you read ascript or try to work through a bug, pay special attention to how each expression (variable, statement, object property) evaluates. I guarantee that as you learn JavaScript (or any lan- guage), you will end up scratching your head from time to time because you haven t stoppedto examine how expressions evaluate when a particular kind of value is required in a script. Data Type ConversionsI mentioned earlier that the type of data in an expression can trip up some script operationsif the expected components of the operation are not of the right type. JavaScript tries its bestto perform internal conversions to head off such problems, but JavaScript cannot read yourmind. If your intentions differ from the way JavaScript treats the values, you won t get theresults you expect. A case in point is adding numbers that may be in the form of text strings. In a simple arith- metic statement that adds two numbers together, you get the expected result: 3 + 3 // result = 6But if one of those numbers is a string, JavaScript leans toward converting the other value toa string thus turning the plus sign s action from arithmetic addition to joining strings. Therefore, in the statement3 + 3 // result = 33 the string-ness of the second value prevails over the entire operation. The first value isautomatically converted to a string, and the result joins the two strings. Try this yourself inThe Evaluator Jr. If I take this progression one step further, look what happens when another number is addedto the statement: 3 + 3 + 3 // result = 63 This might seem totally illogical, but there is logic behind this result. The expression is evalu- ated from left to right. The first plus operation works on two numbers, yielding a value of 6.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision virtual web hosting services

Web design portfolio - 63Chapter 6Programming Fundamentals, Part ITesting JavaScript EvaluationYou can

Sunday, April 22nd, 2007

63Chapter 6Programming Fundamentals, Part ITesting JavaScript EvaluationYou can begin experimenting with the way JavaScript evaluates expressions with the help of TheEvaluator Jr. (seen in the following figure), an HTML page you can find on the companionCD-ROM. (I introduce the Senior version in Chapter 13.) Enter any JavaScript expression into thetop text box, and either press Enter/Return or click the Evaluate button. The Evaluator Jr. for testing expression evaluation. The Evaluator Jr. has 26 variables (lowercase athrough z) predefined for you. Therefore, you canassign values to variables, test comparison operators, and even do math here. Using the agevari- able examples from earlier in this chapter, type each of the following statements into the uppertext box and observe how each expression evaluates in the Results field. Be sure to observe case- sensitivity in your entries. The trailing semicolons are optional in The Evaluator. a = 45; a; b = a 15; b; a b; a > b; To start over, click the Reload button.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

62Part IIJavaScript TutorialMy preference is for (Most popular web site) the second

Saturday, April 21st, 2007

62Part IIJavaScript TutorialMy preference is for the second version. I find it easier to type as I write JavaScript code andeasier to read later. In fact, because of the potential conflict with future one-word keywords, using multiword combinations for variable names is a good idea. Multiword combinations areless likely to appear in the reserved word list. Variable names have a couple of other important restrictions. Avoid all punctuation symbolsexcept for the underscore character. Also, the first character of a variable name cannot be anumeral. If these restrictions sound familiar, it s because they re identical to those for HTMLelement identifiers described in Chapter 4. Expressions and EvaluationAnother concept closely related to the value and variable is expression evaluation perhapsthe most important concept of learning how to program a computer. We use expressions in our everyday language. Remember the theme song of The BeverlyHillbillies? Then one day he was shootin at some foodAnd up through the ground came a-bubblin crudeOil that is. Black gold. Texas tea. At the end of the song, you find four quite different references ( crude, oil, black gold, and Texas tea ). They all mean oil. They re all expressionsfor oil. Say any one of them andother people know what you mean. In our minds, we evaluatethose expressions to mean onething: oil. In programming, a variable always evaluates to its contents, or value. For example, afterassigning a value to a variable, such asvar myAge = 45; any time the variable is used in a statement, its value (45) is automatically applied to what- ever operation that statement calls. Therefore, if you re 15 years my junior, I can assign avalue to a variable representing your age based on the evaluated value of myAge: var yourAge = myAge 15; The variable, yourAge, evaluates to 30 the next time the script uses it. If the myAgevaluechanges later in the script, the change has no link to the yourAgevariable because myAgeevaluated to 45 when it was used to assign a value to yourAge. Expressions in script1.htmYou probably didn t recognize it at the time, but you saw how expression evaluation came inhandy in your first script of Chapter 3. Recall the second document.write()statement: document.write( of + navigator.appName + . ); The document.write()method (remember, JavaScript uses the term methodto mean com- mand) requires a parameter in the parentheses: the text string to be displayed on the Webpage. The parameter here consists of one expression that joins three distinct strings: of navigator.appName .
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

Web design online - 61Chapter 6Programming Fundamentals, Part ICreating a variableYou have

Saturday, April 21st, 2007

61Chapter 6Programming Fundamentals, Part ICreating a variableYou have a couple of ways to create a variable in JavaScript, but one covers you properly inall cases. Use the varkeyword, followed by the name you want to give that variable. Therefore, to declarea new variable called myAge, the JavaScript statement isvar myAge; That statement lets the browser know that you can use that variable later to hold informationor to modify any of the data in that variable. To assign a value to a variable, use one of the assignment operators.The most common one byfar is the equal sign. If I want to assign a value to the myAgevariable at the same time I declareit (a combined process known as initializing the variable), I use that operator in the samestatement as the varkeyword: var myAge = 45; On the other hand, if I declare a variable in one statement and later want to assign a value toit, the sequence of statements isvar myAge; myAge = 45; Use the varkeyword only for declaration or initialization once for the life of any variablename in a document. A JavaScript variable can hold any value type. Unlike many other languages, you don t haveto tell JavaScript during variable declaration what type of value the variable will hold. In fact, the value type of a variable can change during the execution of a program. (This flexibilitydrives experienced programmers crazy because they re accustomed to assigning both a datatype and a value to a variable.) Variable namesChoose the names you assign to variables with care. You ll often find scripts that use vaguevariable names, such as single letters. Other than a few specific times where using letters is acommon practice (for example, using ias a counting variable in repeat loops in Chapter 7), Irecommend using names that truly describe a variable s contents. This practice can help youfollow the state of your data through a long series of statements or jumps, especially for com- plex scripts. A number of restrictions help instill good practice in assigning names. First, you cannot useany reserved keyword as a variable name. That includes all keywords currently used by thelanguage and all others held in reserve for future versions of JavaScript. The designers ofJavaScript, however, cannot foresee every keyword that the language may need in the future. By using the kind of single words that currently appear in the list of reserved keywords (seeAppendix B), you always run a risk of a future conflict. To complicate matters, a variable name cannot contain space characters. Therefore, one-wordvariable names are fine. Should your description really benefit from more than one word, youcan use one of two conventions to join multiple words as one. One convention is to place anunderscore character between the words; the other is to start the combination word with alowercase letter and capitalize the first letter of each subsequent word within the name Irefer to this as the interCap format. Both of the following examples are valid variable names: my_agemyAge
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision best web hosting services

60Part IIJavaScript (Apache web server) Tutorialof letters is a value. A

Saturday, April 21st, 2007

60Part IIJavaScript Tutorialof letters is a value. A number is a value. The setting of a checkbox (whether it is checkedornot) is a value. In JavaScript, a value can be one of several types. Table 6-1 lists JavaScript s formal datatypes, with examples of the values you will see displayed from time to time. Table 6-1: JavaScript Value (Data) TypesTypeExampleDescriptionString Howdy A series of characters inside quote marksNumber4.5Any number not inside quote marksBooleantrueA logical true or falseNullnullCompletely devoid of any content, but a value just the sameObjectA software thing that is defined by its properties and methods(arrays are also objects) FunctionA function definitionA language that contains these few data types simplifies programming tasks, especially thoseinvolving what other languages consider to be incompatible types of numbers (integers ver- sus real or floating-point values). In some definitions of syntax and parts of objects later inthis book, I make specific reference to the type of value accepted in placeholders. When astring is required, any text inside a set of quotes suffices. You will encounter situations, however, in which the value type may get in the way of asmooth script step. For example, if a user enters a number into a form s text input field, thebrowser stores that number as a string value type. If the script is to perform some arithmeticon that number, you must convert the string to a number before you can apply the value toany math operations. You see examples of this later in this lesson. VariablesCooking up a dish according to a recipe in the kitchen has one advantage over cooking upsome data in a program. In the kitchen, you follow recipe steps and work with real things: car- rots, milk, or a salmon fillet. A computer, on the other hand, follows a list of instructions towork with data. Even if the data represents something that looks real, such as the textentered into a form s input field, once the value gets into the program, you can no longerreach out and touch it. In truth, the data that a program works with is merely a collection of bits (on and off states) in your computer s memory. More specifically, data in a JavaScript-enhanced Web page occu- pies parts of the computer s memory set aside for exclusive use by the browser software. Inthe olden days, programmers had to know the numeric address in memory (RAM) where avalue was stored to retrieve a copy of it for, say, some addition. Although the innards of a pro- gram have that level of complexity, programming languages such as JavaScript shield youfrom it. The most convenient way to work with data in a script is to first assign the data to a variable. It s usually easier to think of a variable as a basket that holds information. How long the vari- able holds the information depends on a number of factors. But the instant a Web page clearsthe window (or frame), any variables it knows about are immediately discarded.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision virtual web hosting services

Web hosting companies - ProgrammingFundamentals, PartIThe tutorial breaks away from HTML and

Saturday, April 21st, 2007

ProgrammingFundamentals, PartIThe tutorial breaks away from HTML and documents for a while asyou begin to learn programming fundamentals that apply to prac- tically every scripting and programming language you will encounter. Here, you start learning about variables, expressions, data types, andoperators things that might sound scary if you haven t pro- grammed before. Don t worry. With a little practice, you will becomequite comfortable with these terms and concepts. What Language Is This? The language you re studying is called JavaScript. But the languagehas some other names that you may have heard. JScript isMicrosoft s name for the language. By leaving out the ava, the com- pany doesn t have to license the Java name from its trademarkowner: Sun Microsystems. A standards body called ECMA (pronounced ECK-ma) now governsthe specifications for the language (no matter what you call it). Thedocument that provides all of the details about the language is knownas ECMA-262(it s the 262nd standard published by ECMA). BothJavaScript and JScript are ECMA-262 compatible. Some earlierbrowser versions exhibit very slight deviations from ECMA-262 (whichcame later than the earliest browsers). The most serious discrepan- cies are noted in the core language reference in Part IV of this book. Working with InformationWith rare exception, every JavaScript statement you write doessomething with a hunk of information data. Data may be text infor- mation displayed on the screen by a JavaScript statement or theon/off setting of a radio button in a form. Each single piece of infor- mation in programming is also called a value. Outside of program- ming, the term valueusually connotes a number of some kind; in theprogramming world, however, the term is not as restrictive. A string66CHAPTER …In This ChapterWhat variables are to use themWhy you must learnhow to evaluateexpressionsHow to convert datafrom one type toanotherHow to use basicoperators …
Note: In case you are looking for affordable webhost to host and run your servlet application check Vision ecommerce web hosting services

57Chapter 5Scripts and HTML DocumentsListing (Web hosting packages) 5-9:How Does This

Friday, April 20th, 2007

57Chapter 5Scripts and HTML DocumentsListing 5-9:How Does This Page Work? Enter lowercase letters for conversion to uppercase:



Note: In case you are looking for affordable webhost to host and run your web application check Vision cheap hosting services

56Part IIJavaScript (Crystaltech web hosting) Tutorialoffered user interaction. In the end,

Friday, April 20th, 2007

56Part IIJavaScript Tutorialoffered user interaction. In the end, both authors have working applications that look equallyprofessional. Beyond the DOM, however, real programming nibbles its way into the scripting world. That s because scripts (and programs) work with more than just objects. When I said earlierin this lesson that each statement of a JavaScript script does something, that something involves dataof some kind. Data is the information associated with objects or other pieces ofinformation that a script pushes around from place to place with each statement. Data takes many forms. In JavaScript, the common incarnations of data are numbers; text(called strings); objects (both from the object model and others you can create with scripts); and trueand false(called Booleanvalues). Each programming or scripting language determines numerous structures and limits for eachkind of data. Fortunately for newcomers to JavaScript, the universe of knowledge necessaryfor working with data is smaller than in a language such as Java. At the same time, what youlearn about data in JavaScript is immediately applicable to future learning you may undertakein any other programming language don t believe for an instant that your efforts in learningscripting will be wasted. Because deep down scripting is programming, you need to have a basic knowledge of funda- mental programming concepts to consider yourself a good JavaScript scripter. In the next twolessons, I set aside most discussion about the DOM and focus on the programming principlesthat will serve you well in JavaScript and future programming endeavors. Exercises1.Write the complete script tag set for a script whose lone statement isdocument.write( Hello, world. ); 2.Build an HTML document and include the answer to the previous question such thatthe page executes the script as it loads. Open the document in your browser to test theresults. 3.Add a comment to the script in the previous answer that explains what the script does. 4.Create an HTML document that displays an alert dialog box immediately after the pageloads and displays a different alert dialog box when the user clicks a form button. 5.Carefully study the document in Listing 5-9. Without entering and loading the docu- ment, predicta.What the page looks likeb.How users interact with the pagec.What the script doesThen type the listing into a text editor as shown (observe all capitalization and punctu- ation). Do not type a carriage return after the = sign in the upperMefunction state- ment; let the line word-wrap as it does in the following listing.It s okay to use acarriage return between attribute name/value pairs, as shown in the first tag. Save the document as an HTML file, and load the file into your browser to see how wellyou did.
Note: If you are looking for cheap webhost to host and run your apache application check Vision jboss web hosting services

55Chapter 5Scripts and HTML DocumentsFigure 5-2:The Mozilla 1.4 (Cheapest web hosting)

Friday, April 20th, 2007

55Chapter 5Scripts and HTML DocumentsFigure 5-2:The Mozilla 1.4 JavaScript console window. Safari 1.0 records script errors, but it s not obvious how to read them. You must first enableSafari s Debug menu by typing the following command in the Terminal application: defaults write com.apple.Safari IncludeDebugMenu 1 Then, each time you launch Safari, choose the Log JavaScript Exceptions item in the Debugmenu. Open the MacOS X Console application window, where JavaScript error messagesappear amid other Console logging messages. With luck, future versions will be more developer-friendly. Understanding error messages and doing something about them is a very large subject, reserved for advanced discussion in Chapter 45 on the CD-ROM. During this tutorial, how- ever, you can use the error messages to see if you have perhaps mistyped a script from a list- ing in the book. Scripting versus ProgrammingYou may get the impression that scripting is easier than programming. Scripting simplysounds easier or more friendly than programming. In many respects, this is true. One of myfavorite analogies is the difference between a hobbyist who builds model airplanes fromscratch and a hobbyist who builds model airplanes from commercial kits. The from scratch hobbyist carefully cuts and shapes each piece of wood and metal according to very detailedplans before the model starts to take shape. The commercial kit builder starts with many pre- fabricated parts and assembles them into the finished product. When both builders are fin- ished, you may not be able to tell which airplane was built from scratch and which one cameout of a box of components. In the end, both builders used many of the same techniques tocomplete the assembly, and each can take pride in the result. As you ve seen with the Document Object Model, the browser gives scripters many prefabri- cated components with which to work. Without the browser, you d have to be a pretty goodprogrammer to develop from scratch your own application that served up content and
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services