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.

The Future Value application

You have now learned enough about JavaScript to write simple applications of your own. To give you a better idea of how to do that, this chapter ends by presenting the Future Value application.

The Future Value application is shown in the web browser in figure 2-19. This application asks the user for three numbers that are needed for calculating the future value of a monthly investment. The user types these values into the first three text boxes and clicks the Calculate button. The application then parses the user entries into numbers, performs basic data validation, and either displays an error message in an alert box or the result of the calculation in the Future Value text box. In this figure, an error message is displayed because the user has entered an invalid investment amount ($100).

The XHTML and JavaScript for this application are described next. Although the CSS isn't shown, it is available in the downloadable applications for this book.

The XHTML code

The XHTML code for this application is an XHTML 1.0 Transitional document. The head section sets the title of the page, loads an external CSS file with the <link> tag, and loads an external JavaScript file with the <script> tag.

In the body of the page, there are four text boxes and one button. The text boxes have investment, rate, years, and futureValue as their ids. The button has calculate as its id. The fourth text box also has its disabled property set. As a result, the user can't type in the text box, but JavaScript can display a value in it.

Notice that by keeping the CSS and JavaScript code in separate files, the XHTML file is uncluttered. As a result, it is easy to see the content and structure of the page, and the three files will be easier to maintain. After the XHTML file for an application like this is complete, different developers could work on the CSS and JavaScript files to help speed development time.

The Future Value application in a web browser

The XHTML file

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" type="text/css" href="future_value.css" />
<script type="text/javascript" src="future_value.js"></script>
</head>
<body>
<div id="content">
<h1>Future Value Calculator</h1>
<p>Enter the values below and click "Calculate".</p>
<label for="investment">Monthly Investment:</label>
<input type="text" id="investment" /><br />
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate" />%<br />
<label for="years">Number of Years:</label>
<input type="text" id="years" /><br />
<label for="futureValue">Future Value:</label>
<input type="text" id="futureValue" disabled="disabled" /><br />
<label>&nbsp;</label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>

Figure 2-19 The Future Value application (part 1 of 2)

The JavaScript code

Part 2 of this figure shows the JavaScript file for the Future Value application.Because you've already learned how to write all of the statements in this application, you should be able to understand this code without too much trouble. But here's a quick description of the application.

The application defines three functions. The first is the $ function that's used as a shortcut to the getElementById method. The second function is the event handler that will run when the Calculate button is clicked. The third function is the event handler for the onload event.

The third function runs after the page is loaded and the DOM is built. Its first statement assigns the calculate_click function as the onclick event handler for the Calculate button. Its second statement uses the focus method to put the cursor in the investment text box.

When the user clicks the Calculate button, the calculate_click function is executed. This function starts by parsing the contents of the first three text boxes and storing those values in appropriately named variables. Then, this function moves an empty string into the futureValue text box. That clears any value that was displayed by a previous calculation.

Next, this function uses an if statement to check each of the three user entries to see whether it is not numeric or it is less than or equal to zero. If one of these conditions is true, the alert method is used to display an appropriate error message and the if statement ends.

However, if all three user entries are valid, the else clause is executed. The code in this clause first converts the annual interest rate to a monthly rate and the years to months. Then, it uses those values in a for statement that calculates the future value. When the for statement ends, the future value is rounded to two decimal places and displayed in the futureValue text box.

If you understand all of this code, you're ready to write some significant applications. However, you should be aware that this application can be improved in several ways. For example, you could check to make sure that the user entries are not only valid but reasonable by making sure that the annual interest rate is less than 20 and the number of years is less than 50. You could also add a Clear button and an event handler that clears the first three text boxes when the user clicks the button. Improvements like these make an application easier to use, and you already have the skills for adding these improvements.

Another improvement could be made in the XHTML code. As it is now, if a browser has JavaScript disabled, the users will be able to enter values into the application, but nothing will happen when they click the Calculate button. To fix that, you could add a <noscript> tag that displays a message that says that the application won't work without JavaScript.

The JavaScript file

var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
// 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 an empty string.
$("futureValue").value = "";
// Test the three input values for validity.
if (isNaN(investment) || investment <= 0) {
alert("Investment must be a valid number\nand greater than zero.");
} else if(isNaN(annualRate) || annualRate <= 0) {
alert("Annual rate must be a valid number\nand greater than zero.");
} else if(isNaN(years) || years <= 0) {
alert("Years must be a valid number\nand greater than zero.");
// If all input values are valid, calculate the future value.
} else {
var monthlyRate = annualRate / 12 / 100;
var months = years * 12;
var futureValue = 0;
for ( i = 1; i <= months; i++ ) {
futureValue = ( futureValue + investment ) *
(1 + monthlyRate);
}
// 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();
}

Figure 2-19 The Future Value application (part 2 of 2)

Total Pages : 20 1617181920

comments