jQuery #4
Part: Client-side data validation
Let's return to our loan payment example. We will still use JavaScript to compute the loan payment. However, we will let jQuery validate the input data. Input is:
Create labeled input boxes for (1) Loan Amount, (2) Annual Interest Rate, and (3) Years.
Create a button with the label "Compute Payment".
Create a paragraph for the loan amount.
You must write code to:
- When the loan amount or annual interest rate or years text box gets the focus, set its background color to a shade of yellow to help the user identify where he is on the page.
- When the loan amount or annual interest rate or years text box loses the focus, set its background color back to white.
- Bad Numbers: When the user clicks on the Compute Payment button, pick off the contents of the three text boxes and validate the numbers. If anything is not a number (NaN—see the isNan function), change the background color of the text box to a light shade of red.
- Out of range numbers:
- The loan amount must be a positive number. If it is 0 or negative, change the background of the loan amount box to a light shade of red.
- The annual interest rate must be >= 0 and <=30.If it is <0 or >30, change the background of the annual interest rate box to a light shade of red.
- The number of years to pay off the loan must be an integer from 1 to 40. If it is < 1 or > 40, change the background of the years box to a light shade of red.
- Also, when a number is out of range, you must inform the user. You can use an alert box or you can add some HTML with an error message. An alert box is probably the easier of the two. Note that "Invalid number" or "Error" are not appropriate error messages. Your error message should tell the user which variable is incorrect and why it is incorrect.
- If all of the numbers are valid, compute the monthly payment.
- The formula requires the rate per period (in our case, a period is a month). Remember that the rate must be divided by 100 to make it a percent and then divided by 12 to get the monthly rate. So if the user types in 6 (for 6% annual rate), divide it by 100 to get 0.06, and then divide by 12 to get 0.005. This is the rate per period.
- The formula requires the number of payment periods. Since we are doing monthly payments, we must multiply the years by 12 to get the number of payments.
- The formula for finding the payment on a loan can be found online.
Your screen should look something like this. I added a minimal amount of CSS:
jQuery used:
Events:
- click
- focus
- blur
Functions/methods:
- parseFloat
- parseInt
- val
- isNaN
- css
- Math.pow
- alert/console.log
- toFixed
Also regular JavaScript:
- if statement
- variables
Page 1 of 2