Example: Computing Loan Payments with JavaScript
Example 1-3 is a listing of a complete, nontrivial JavaScript program. The program computes the monthly payment on a home mortgage or other loan, given the amount of the loan, the interest rate, and the repayment period. As you can see, the program consists of an HTML form made interactive with JavaScript code. Figure 1-3 shows what the HTML form looks like when displayed in a web browser. But the figure can only capture a static snapshot of the program. The addition of JavaScript code makes it dynamic: whenever the user changes the amount of the loan, the interest rate, or the number of payments, the JavaScript code recomputes the monthly payment, the total of all payments, and the total interest paid over the lifetime of the loan.

Figure 1-3. A JavaScript loan payment calculator
The first half of the example is an HTML form, nicely formatted using
an HTML table. Note that several of the form elements define
onchange
or onclick
event handlers. The web browser
triggers these event handlers when the user changes the input or
clicks on the Compute button
displayed in the form. Note that in each case, the value of the event
handler attribute is a string of JavaScript code: calculate( )
. When the event handler is triggered,
it executes this code, which causes it to call the function
calculate( ).
The calculate( ) function is defined ...