FREE BOOK

Chapter 2: How to code a JavaScript application

Posted by Murach Free Book | Internet & Web November 02, 2009
This chapter presents a subset of JavaScript and DOM scripting that will soon have you writing significant applications. If you don't have any programming experience, this chapter also makes a great aptitude test. If you read it and can do the exercises at the end of the chapter, you're ready for the rest of this book.

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
statement
comment
identifier
reserved word
keyword
camel casing
primitive data type
number data type
integer
decimal value
floating-point number
exponent
string data type
string
empty string
escape sequence
Boolean data type
Boolean value
expression
arithmetic operator
order of precedence
concatenate
variable
declare a variable
assignment statement
assignment operator
compound assignment operator
string literal
numeric literal
object
property
method
instance
constructor function
dot operator
call a method
parameter
argument
object chaining
global object
window object
document object
control statement
conditional expression
relational operator
compound conditional expression
logical operator
if statement
if clause
else if clause
else clause
nested if statements
while statement
while loop
for statement
for loop
function
return statement
call a function
event
event handler

Before you do the exercises for this book...

If you haven't already done so, you should install the Mozilla Firefox browser and install the applications for this book as described in appendix A. Then, if you're new to programming, you should do exercise 2-1. But if you have some programming experience, you can start with exercise 2-2.

Exercise 2-1 Build the Sales Tax application

This exercise is for beginners. It steps you through the process of building the Sales Tax application of chapter 1. This exercise also gives you a chance to do some experimenting, which is a great way to learn JavaScript programming.

Open the files for the Sales Tax application

  1. Start the Firefox browser. Then, use the FileOpen command to open the file named sales_tax.html in the chapter 2 folder for the exercises. If you installed the downloadable applications as in appendix A, the path to that file on a Windows system is:
    C:\murach\javascript\exercises\chapter_02\sales_tax\sales_tax.html
  2. Enter valid numeric values in the first two input boxes and click the Calculate button. Notice that nothing happens.
  3. Use your text editor to open the sales_tax.js file for this application. It is in the same folder as the html file. Then, notice that this file only contains the $ function that's used to get the object for an XHTML element.
  4. Use your text editor to open the sales_tax.html file for this application. Then, note the ids that are used for the text boxes for this application.

Start the event handlers for this application

  1. Start the event handler for the window.onload event by entering this code:
    window.onload = function () {
    alert ("This is the window.onload event handler.");
    }
    Then, save the file, switch to Firefox, click the Reload button, and note the message that's displayed. Or, if nothing happens, check your code, fix it, and try this again. If necessary, you can access the Firefox Error Console as shown in figure 2-3. When you've got this working right, switch back to your editor.
  2. Between the $ function and the window.onload event handler, start a function named calculate_click by entering this code:
    var calculate_click = function () {
    alert ("This is the calculate_click event handler.");
    }
    Then, save the code, switch to Firefox, click the Reload button, and note that this function isn't executed. That's because it hasn't been called. Now, switch to your editor.
  3. Call the calculate_click function from the window.onload event handler by entering this statement after the alert statement:
    calculate_click();
    Then, save the file, switch to Firefox, and click the Reload button. This time, two message boxes should be displayed: one by the window.onload event handler and one by the calculate_click function. If this doesn't work, fix the code and try it again. Then, switch to your editor.
  4. Assign the calculate_click function to the click event of the Calculate button by replacing the statement you entered in step 7 with this statement:
    $("calculate").onclick = calculate_click;
    Then, save the file, switch to Firefox, click the Reload button, and click on the Calculate button. If you did everything right, the two message boxes are again displayed. Otherwise, fix the code and try again. Then, switch to your editor.
Finish the calculate_click event handler

After you do each of the steps that follow, switch to Firefox, click the Reload button, and make sure your changes work. Otherwise, fix your code and try again.

  1. Add these statements after the alert statement in the calculate_click function:
    var subtotal = 200;
    var taxRate = 7.5;
    var salesTax = subtotal * (taxRate / 100);
    var total = subtotal + salesTax;
    alert ( "subtotal = " + subtotal + "\n" +
    "taxRate = " + taxRate + "\n" +
    "salesTax = " + salesTax + "\n" +
    "total = " + total);
  2. If you have any questions about how variables and arithmetic statements work, review figures 2-7 through 2-9. Then, experiment with any statements that you don't understand in the calculate_click function. To display the results of your statements, you can use alert statements as in step 9.
  3. Replace the statements that you entered in step 9 with these statements:
    var subtotal = parseFloat( $("subtotal").value );
    var taxRate = parseFloat( $("taxRate").value );
    // calculate results
    var salesTax = subtotal * (taxRate / 100);
    salesTax = parseFloat( salesTax.toFixed(2) );
    var total = subtotal + salesTax;
    // display results
    $("salesTax").value = salesTax;
    $("total").value = total.toFixed(2);
    The first two statements will get the user entries; the last two statements will display the results. This is explained in figure 2-13. At this point, the application should work if the user enters valid numbers.
  4. Comment out the two alert statements by entering slashes before them.
  5. 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.
  6. 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.

Exercise 2-2 Enhance the Future Value application

In this exercise, you'll enhance the Future Value application in several ways. That will give you a chance to use some of the skills that you've learned in this chapter.

Test the Future Value application

  1. Start the Firefox browser. Then, open the file named future_value.html in the chapter 2 folder for the exercises. The path to that file on a Windows system is:
    C:\murach\javascript\exercises\chapter_02\future_value\future_value.html
  2. Enter valid numeric values in the three input boxes. For the first test run, keep these values simple like 100 for monthly investment, 12 for annual interest
    rate, and 1 for number of years. Then, click the Calculate button to display a valid result in the fourth text box.
  3. Enter invalid values in the three input boxes and click the Calculate button. Then, respond to the first message box by entering valid data and clicking the Calculate button again. Do the same for the next two message boxes.

Enhance the validity checking

  1. Use your text editor to open the future_value.js file for this application. This file should be in the same folder as the html file (see step 1).
  2. Modify the validity testing for the annual interest rate so it has to be a valid number that's greater than zero and less than or equal to 20. Next, adjust the error message that's displayed to reflect this third validity test.
    To test this enhancement, save the JavaScript file, switch to Firefox, click on the Reload button, enter an interest rate that's greater than 20, and click the Calculate button.
  3. 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

  1. 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.
  2. 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

  1. 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

  1. 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

  1. 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

  1. 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 ToolsOptions 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.

Total Pages : 20 1617181920

comments