Forms that Calculate

It is possible to build simple stand-alone applications using forms and JavaScript. These are of somewhat limited use on their own as JavaScript embedded in HTML pages depends on the services provided by a browser. For example JavaScript cannot maintain data by working with local files. (Of course there are good security reasons for this.) The scripted form below is an example of what you can do with a form and JavaScript. It provides a simple way to calculate your total savings if you invest a fixed amount every month for a given number of years. The form also provides some fictitious Guaranteed Investment Certificate interest rates with some conditions. Try it out:

Total Savings Calculator

(fixed interest and fixed monthly deposits)

 Number of Years: Monthly Deposit Amount: GIC Type: Grade A, No Fixed Term Certificate: 5% Grade B, Minimum 2 Year Certificate: 6% Grade B, Minimum 3 Year Certificate: 6.2% Grade C, Minimum 5 Year Certificate: 7% Total Savings:

There are at least three ways in which this form could be improved:

1. If you enter a nonnumeric value in the year or monthly deposit fields the total savings are reported as NaN (Not a number). It would be better to explain what went wrong to the user when this happens. The normal way to do this is to check their input character by character - looking for and reporting illegal characters. It would also be helpful to allow the user to enter a dollar sign (\$) and a decimal point in the monthly deposit field. If you allow a dollar sign it must be removed before the value is converted to a number.
2. Similarly, entering bad data in the year field will produce NaN or an incorrect result. For example if a user enters -100 in the deposit field. Ideally, user data of this type would be caught and reported.
3. The total savings are reported as numbers such as: 1091510.254092961 and really should be rounded to the nearest cent. For example it would be better to report: \$1091510.25, or better still: \$1,091,510.25.

Of course the form does not adjust for varrying inflation rates or give you the option to deposit different amounts over different periods of time. To keep the calculation and the form relatively simple we will just pretend there is no such thing as inflation and no other means of investing funds beyond fixed amount monthly deposits. Below is the complete source code for this example. The comments in the code provide an explanation of how it works.

 ``` Total Value of Regular Monthly Deposits

Total Savings Calculator

(fixed interest and fixed monthly deposits)

Number of Years:
Monthly Deposit Amount:
GIC Type:

Total Savings:

```