HTML and CSS Reference
In-Depth Information
Adding the Monthly Payment Calculation
With the JavaScript code for the form validation complete, the next step is to add code
to the CalcLoanAmt() function to calculate the monthly payment. First, a statement
must be added to the CalcLoanAmt() function to call a user-defined function named
monthlyPmt(), which calculates the monthly payment. The monthlyPmt() function uses
the valid data in the form and calculates the monthly payment. The result is the monthly
payment, which is returned as a floating-point value.
The placement of the monthlyPmt() function within the CalcLoanAmt() function is
important so that, if a value in a text field is invalid, the function does not attempt to process
invalid data and return an undefined result. To place this function properly, one more else
statement must be added to the CalcLoanAmt() function, as shown in Table 10-17.
Table 10-17 Code to Call the monthlyPmt() Function
Line
Code
60
else {
61
var monthlyPmtAmt = monthlyPmt(loanAmt,loanRate,loanYears)
62
homeLoanForm.Payment.value=monthlyPmtAmt.toString()
63
}
Line 60 adds an additional else statement to the nested if…else statements. Line 61
calls the monthlyPmt() function and passes the loan amount, interest rate, and number of
years for the loan as variables: loanAmt, loanRate, and loanYears. The result is stored in a
temporary variable named monthlyPmtAmt. Line 62 assigns the monthly payment result
to the Payment text field on the form using the toString() method to convert the value to
a string for display in the text field and for use in the formatting user-defined function,
which will be written later. Line 63 is the closing brace for the additional else statement.
To Enter Code to Call the monthlyPmt() Function
The following step enters the final else statement and the function call that passes the required values to the
monthlyPmt() function.
1
Click the beginning of
line 60 and then press
the e n t e r key to insert
a blank line.
ends the else
portion of if…else
statement
statement added to
call monthlyPmt()
function to calculate
payment
Click the blank line just
inserted (line 60).
monthlyPmt result
assigned to Payment
text field on form
do not press
the e n t e r key
Press the
s p a c e b a r
to indent under
the closing brace in
line 59, then enter the
JavaScript code shown in Table 10-17 to call the monthlyPmt()
user-defined function and assign the result to the payment
text field, but do not press the e n t e r key (Figure 10-24).
If I try to execute this Web page now, will an error occur?
Yes, because the monthlyPmt() user-defined function has not been written and entered.
Figure 10-24
 
Search WWH ::




Custom Search