Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
murach’s
JavaScript
and DOM Scripting
(Chapter 2)
Thanks for downloading this chapter from Murach’s JavaScript and DOM Scripting. We
hope it will show you how easy it is to learn from any Murach book, with its paired-pages
presentation, its “how-to” headings, its practical coding examples, and its clear, concise
style.
To view the full table of contents for this book, you can go to our website. From there,
you can read more about this book, you can find out about any additional downloads that
are available, and you can review our other books on web development.
Thanks for your interest in our books!
Contents
Introduction xiv
Reference Aids
Appendix A How to set up your computer for this book 745
Index 753
Chapter 2 How to code a JavaScript application 43
2
How to code a JavaScript
application
In this chapter, you’ll learn how to code simple JavaScript applications like the
Sales Tax application in the last chapter. That will get you off to a fast start and
give you the perspective you need for learning rapidly in subsequent chapters.
If you haven’t done much programming, this chapter will move quickly
for you. But if you take it slow and do the exercises, you should master all of
the skills. When you’re finished, you’ll be able to write significant JavaScript
applications of your own.
How to retest a web page after you change the source code
• To reload the edited file for the page, click the Reload or Refresh button. Then, run the
application.
• Sometimes, clicking the Reload or Refresh button won’t clear the browser memory
completely so your changes won’t work correctly. In that case, you may need to close
the browser window and reopen the application.
Description
• This chapter shows how to write JavaScript applications, and the next chapter shows you
how to test and debug them.
The source code that’s displayed when you click on the link
Description
• The Error Console in Firefox is used to display errors, warnings, and messages gener-
ated by web pages. That includes messages caused by errors in JavaScript code.
• The buttons at the top of the Error Console let you display all errors, just fatal errors,
just warnings, or just messages. The Clear button removes all errors from the console.
• If you click the link to the file in the Error Console, Firefox will display the code and
highlight the line at which the error occurred. You will not, however, be able to edit the
file.
Description
• You can have multiple <script> tags in a web page. They are executed in the order that
they appear in the document, unless the defer attribute has been used.
• In the body of a document, the <script> tag is replaced by the output of the code. The
<noscript> tag is used to display content when JavaScript is disabled or not available.
• The XHTML document must be valid before and after all scripts have been executed.
A single-line comment
nextYear = thisYear + 1; // Determine what the next year is
A multi-line comment
/* The following line determines what the
next year is by adding 1 to the current year
*/
nextYear = thisYear + 1;
Description
• JavaScript has a syntax that’s similar to the syntax of Java.
• JavaScript provides two forms of comments, which are ignored when the JavaScript is
executed.
• In some cases, JavaScript will try to correct a missing semicolon by adding one at the end
of a split line. This can cause errors. To prevent this, put a semicolon at the end of each
statement, and follow the guidelines above for splitting a statement.
Description
• Identifiers are the names given to variables, functions, objects, properties, and methods.
How the \n escape sequence can be used to start a new line in a string
"A valid variable name\ncannot start with a number."
// represents the string: A valid variable name
// cannot start with a number.
Description
• JavaScript provides for just three primitive data types. These data types are used for
storing numbers, strings, and Boolean values.
Description
• To code an arithmetic expression, you can use the arithmetic operators to operate on two
or more values.
• An arithmetic expression is evaluated based on the order of precedence of the operators.
• To override the order of precedence, you can use parentheses.
• To concatenate two or more strings, you can use the + operator.
• Since the plus sign can be used for both numeric and string expressions, JavaScript looks
at the data types to determine which operation to perform. If both values are numbers,
JavaScript adds. If both values are strings, JavaScript concatenates. If one value is a
number and one is a string, JavaScript converts the number to a string and concatenates.
Description
• A variable stores a value that can change as the program executes.
• To declare a variable, code the keyword var and a variable name. To declare more than
one variable in a single statement, code var and the variable names separated by com-
mas.
• To assign a value to a variable, you use an assignment statement that consists of the
variable name, an assignment operator, and an expression. When appropriate, you can
declare a variable and assign a value to it in a single statement.
• Within an expression, a string literal is enclosed in quotation marks. A numeric literal is
a valid integer or number that isn’t enclosed in quotation marks.
• When the expression in an assignment statement contains both strings and numbers, the
numbers are converted to strings before the expression is evaluated.
Description
• An object has properties that represent attributes like the width of a window or the value
that’s in an XHTML element.
• An object also has methods that do functions that are related to the object.
• When you call a method, you may need to pass one or more parameters (or arguments)
to it by coding them within the parentheses after the method name. If the method
requires more than one parameter, you must separate them with commas.
• Object chaining lets you access the properties or methods of objects that are nested
inside other objects.
• Often, an object is stored in the property of another object or returned by a method of
another object.
and then it gets the value property of that object. The second statement gets the
location property of the window object, which is a string, and then uses the
toLowerCase method of the string object to convert the location property to
lowercase letters.
If this is confusing right now, you’re going to see many more examples of
the use of objects and object chaining in the rest of this chapter. So by the end
of this chapter, you should become comfortable with the use of object chaining.
Examples that use the properties and methods of the window object
alert("Invalid entry."); // displays "Invalid entry."
var userEntry = prompt(errorMessage,100); // accepts user entry
parseInt("12345.67"); // returns the integer 12345
parseFloat("12345.67"); // returns the floating point value 12345.67
parseFloat("Ray Harris"); // returns NaN
Description
• The window object is the global object when JavaScript is used in a web browser. It
provides the global and browser properties and methods.
• JavaScript lets you omit the object name and period when referring to the window
object.
• The document object is the object that allows you to work with the DOM.
Examples
var balance = 2384.55678; // creates a number object named balance
alert ( balance.toFixed(2) ); // displays 2384.56
// balance is still 2384.55678
balance = parseFloat( balance.toFixed(2) ); // balance is now 2384.56
Examples
var guest = "Ray Harris"; // creates a string object named employee
alert ( guest.toUpperCase() ); // displays "RAY HARRIS"
alert ( guest.substr(0,3) ); // displays "Ray"
guest = guest.substr(4,6); // guest is now "Harris"
Examples
var today = new Date(); // creates a Date object named today
// assume the current date is 09/20/2008
alert ( today.toDateString() ); // displays Sat Sep 20 2008
alert ( today.getFullYear() ); // displays 2008
alert ( today.getMonth() ); // displays 8, not 9, for September
Description
• When you declare a number or string variable, a Number or String object is created.
Then, you can use the Number or String methods with the variable.
• To create a Date object, assign new Date() to a variable. Then, you can use the Date
methods with the variable.
Figure 2-12 How to use the Number, String, and Date objects
68 Section 1 Introduction to JavaScript programming
How to use the value property to get the value in a text box
In two statements
// Store a reference to the text box
var rateTextbox = document.getElementById("rate");
// Get the value and convert it to a number
var rate = parseFloat( rateTextbox.value );
How to use the focus method to move the cursor to a text box
document.getElementById("investment").focus();
Description
• When you use a text box to get numeric data that you’re going to use in calculations, you
need to use either the parseInt or parseFloat method to convert the string data to numeric
data.
• To place the cursor in a text box, you use the focus method of the Textbox object.
Figure 2-13 How to get and display data with a Textbox object
70 Section 1 Introduction to JavaScript programming
Description
• A conditional expression uses the relational operators to compare the results of two
expressions.
• A compound conditional expression joins two or more conditional expressions using the
logical operators.
• The isNaN method tests whether a string can be converted to a number. It returns true if
the string is not a number and false if the string is a number.
Note
• Confusing the assignment operator ( = ) with the equality operator ( ==) is a common
programming error.
A nested if statement
if ( isNaN(totalMonths) || totalMonths <= 0 ) {
alert ("Please enter a number of months greater than zero.");
} else {
var years = parseInt ( totalMonths / 12 );
var months = totalMonths % 12;
if ( years == 0 ) {
alert ( "The investment time is " + months + " months.");
} else if ( months == 0 ) {
alert ( "The investment time is " + years + " years.");
} else {
var message = "The investment time is " + years + " years ";
message += "and " + months + " months.";
alert(message);
}
}
Description
• An if statement can include multiple else if clauses and one else clause at the end. The if
clause of the statement executes one or more statements if its condition is true.
• The else if clause is executed when the previous condition or conditions are false. The
statement or statements within an else if clause are executed if its condition is true.
• The else clause is executed when all previous conditions are false.
• You can code one if statement within the block of statements of an if, else if, or else
clause in another if statement. This is referred to as nested if statements.
Description
• The while statement is used to create a while loop that contains a block of code that is
executed as long as a condition is true. This condition is tested at the beginning of the
loop. When the condition becomes false, JavaScript skips to the code after the while
loop.
• The for statement is used to create a for loop that contains a block of code that is ex-
ecuted a specific number of times.
• When you code one loop within another loop, you are coding nested loops.
• JavaScript also offers two other looping structures, which you’ll learn about in chapter 8.
How to call a function with two parameters that doesn’t return a value
displayEmail( "mike", "murach.com");
Description
• A function is a block of code that you can use multiple times in an application. It can
require one or more parameters.
• A function can return a value to the code that called it by using the return statement.
When a return statement is executed, the function returns the specified value and ends.
• The code that calls a function may discard the returned value, store it in a variable, or
use it in an expression.
• If a function ends without encountering a return statement, it returns a special value
called undefined.
Common events
Object Event Occurs when…
button onclick The button is clicked.
window onload The document has been loaded into the browser.
// This is the event handler for the onclick event of the button.
var display_click = function () {
alert( "You clicked the button.");
}
// This is the event handler for the onload event of the page.
// It is executed after the page is loaded and the DOM has been built.
window.onload = function () {
// This statement assigns the event handler named display_click
// to the onclick event of the XHTML object named btnDisplay
$("btnDisplay").onclick = display_click;
}
</script>
</head>
<body>
<p><input type="button" value="Display Message" id="btnDisplay" /></p>
</body>
</html>
Description
• An event handler is executed when the event that triggers it occurs.
• The event handler for the onload event of the window object can be used to assign event
handlers to other events after the DOM has been built.
<body>
<div id="content">
<h1>Future Value Calculator</h1>
<p>Enter the values below and click "Calculate".</p>
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>
// Get the user entries from the first three text boxes.
var investment = parseFloat( $("investment").value );
var annualRate = parseFloat( $("rate").value );
var years = parseInt( $("years").value );
// Set the value of the fourth text box to the future value
// but round it to two decimal places.
$("futureValue").value = futureValue.toFixed(2);
}
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("investment").focus();
}
Perspective
The goal of this chapter has been to get you started with JavaScript and to get
you started fast. Now, if you understand the Future Value application, you’ve come
a long way. You should also be able to write basic JavaScript applications of your
own. Keep in mind, though, that this chapter is just an introduction to the
JavaScript essentials that will be expanded upon by the chapters in section 2.
Terms
syntax property
statement method
comment instance
identifier constructor function
reserved word dot operator
keyword call a method
camel casing parameter
primitive data type argument
number data type object chaining
integer global object
decimal value window object
floating-point number document object
exponent control statement
string data type conditional expression
string relational operator
empty string compound conditional expression
escape sequence logical operator
Boolean data type if statement
Boolean value if clause
expression else if clause
arithmetic operator else clause
order of precedence nested if statements
concatenate while statement
variable while loop
declare a variable for statement
assignment statement for loop
assignment operator function
compound assignment operator return statement
string literal call a function
numeric literal event
object event handler
Chapter 2 How to code a JavaScript application 85
13. Check the user entries for validity by entering this code with the statements
that do the calculations in the else clause:
if ( isNaN(subtotal) || isNaN(taxRate) ) {
alert("Please check your entries for validity.");
} else {
// the statements that do the calculations should be here
}
This just checks to make sure that both user entries are numeric before the
calculations are done.
14. At this point, you have a working application, but one that can be improved. If
you would like to improve it, review the code in figure 1-13 of the last chapter
for ideas. For instance, you can check to make sure that each user entry is both
numeric and greater than zero, and you can display a different error message
for each text box. Or, you can add a statement to the window.onload function
that moves the focus to the first text box. When you’re through experimenting,
close the files.
6. Switch back to the JavaScript file in your text editor, modify the validity
testing for the number of years so this value also has to be less than or equal to
50, and modify the error message to reflect this change. Then, save the file,
switch to Firefox, and test this change.
Add a Clear button
7. Use your text editor to open the html file for this application and add a Clear
button below the Calculate button. To do that, you can just copy the XHTML
for the Calculate button and modify the id and value attributes. Then, save the
file, switch to Firefox, and test this change.
8. Switch back to the JavaScript file in your text editor and add an event handler
named clear_click that clears the text boxes when the Clear button is clicked.
This handler should store empty strings in the four text boxes on the page.
After you code the event handler, add a line to the window.onload handler that
assigns the new event handler to the click event. Then, test this change.
Modify the calculation that’s done
9. Change this application so it calculates the future value of a one-time
investment instead of fixed monthly investments. To do that, modify the
XHTML file so the first label reads “One-Time Investment”. Next, modify the
code in the calculate_click event handler so interest is calculated and added to
future value just once each year for the number of years that were entered by
the user. Then, test this change.
Disable and enable the text box for the annual interest rate
10. Modify the JavaScript code in the calculate_click event handler so it disables
the text box for the annual interest rate after it finishes the for loop and
displays the future value. Next, modify the code in the clear_click event
handler so it enables this text box when the Clear button is clicked. Then, test
these changes.
Add the date to the web page
11. Modify the XHTML file so it uses embedded JavaScript as shown in figure 2-4
to display the current date at the bottom of the web page like this:
Today is Thu Oct 23 2009
To do this, you need to use the toDateString method as shown in figure 2-12.
Then, test this change.
Add a <noscript> tag to display a message when JavaScript is disabled
12. Add a <noscript> tag after the embedded <script> tag as shown in figure 2-4.
The noscript tag should display “You must enable JavaScript for this
application.” To test this, use the ToolsÎOptions command in the Firefox
browser to disable JavaScript. When you’re through testing, enable JavaScript
again and close your files.
If you were able to do all of the steps in this exercise, congratulations!
You’re well on your way to learning JavaScript and DOM scripting.
How to build your JavaScript skills
The easiest way is to let Murach’s JavaScript and DOM
Scripting be your guide! So if you’ve enjoyed this chapter, I
hope you’ll get your own copy of the book today. You can use
it to:
• Teach yourself how to use JavaScript and DOM scripting
to create web sites that deliver the dynamic user inter-
faces, fast response times, and special effects that today’s
users expect Mike Murach, Publisher
• Pick up a new skill whenever you want or need to by
focusing on material that’s new to you
• Look up coding details or refresh your memory on forgotten details when you’re
in the middle of developing a web application
• Loan to your colleagues who are always asking you questions about client-side
web programming
To get your copy, you can order online at www.murach.com or call us at
1-800-221-5528 (toll-free in the U.S. and Canada). And remember, when you order
directly from us, this book comes with my personal guarantee:
100% Guarantee