Boonex Social Networking



Javascript Mortage Calculator


The objective of this article is to build our own mortgage calculator that is lean on code; can be styled using CSS; and, is perfectly valid and accessible.

User Input

The user needs to provide us with the following:

  • Principal (Loan Amount in $)
  • Interest Rate (in % per year)
  • Period of Repayment (in Years)

Laying out our Calculator

Our javascript takes the above inputs and calculates the following:

  • Monthly payment
  • Amortization Schedule

HTML Layout

  • We need 3 input text fields for user inputs and a button to trigger the script.
  • We need 2 HTML elements to display our results.
  • For those who have javascript disabled, we need an HTML element to display a message to enable javascript.

Based on the above, the following is the HTML Layout.

HTML Code:
<table width="400" border="0" align="center" cellpadding="6" cellspacing="3">
<tr>
<th align="right"><label for="p">Principal:</label></th>
<td><input name="p" type="text" id="p" value="100000" tabindex="1"></td>
</tr>
<tr>
<th align="right"><label for="i">Interest:</label></th>
<td><input name="i" type="text" id="i" value="8" tabindex="2"></td>
</tr>
<tr>
<th align="right"><label for="y">Years:</label></th>
<td><input name="y" type="text" id="y" value="30" tabindex="3"></td>
</tr>
<tr>
<th align="right">&nbsp;</th>
<td><input type="button" tabindex="4" name="Button" value="Calculate Now..." onClick="calc()"></td>
</tr>
<tr align="center">
<td colspan="2" id="result">&nbsp;</td>
</tr>
<tr>
<td colspan="2" id="amort">&nbsp;</td>
</tr>
<tr>
<td colspan="2" id="mess">Javascript is required for the calculator to work.</td>
</tr>
</table>

Note:The above HTML is written for a transitional doctype. You may want to remove/change deprecated attributes such as align, etc. for the code to be valid if you use a strict doctype.

Calculator Script

Insert into the head section of your document or in a seperate .js file.

The javascript consists of 5 major functions:

  • findObj() - This function is used to find the user input elemets and the result/display elements
  • toCur() - This funtion rounds ours results to two decimal places and adds the Currency sign
  • calc() - This function calculates the monthly payment
  • genHTML() - This function writes out the amortization schedule
  • window.onload - Hides the message if javascript is enabled and focuses on the first input field.
Script Code:
function findObj(n, d) {
         var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
           d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
         if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
         for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
         if(!x && d.getElementById) x=d.getElementById(n); return x;
       }
       function toCur(val,cur) {
       val=(val+"").replace(/,/g,"");
       return  ((cur? cur:"") +
       (Math.round(val*100) +
       (val<0?-0.1:+0.1))/ 100).replace(/(.*.dd)d*/,'$1');
       }
       function calc() {
           var p = findObj('p').value;
           var i = findObj('i').value;
           var y = findObj('y').value;
var numCheck = new RegExp(/^d+(?:.d{0,2})?$/);
           if (!numCheck.test(p) || !numCheck.test(i) || !numCheck.test(y)) {
               alert("Values must be numeric");
           }
           else {
               var iM = i/1200;
               var b = 1;
               var bM =  1+iM;
               for (i=0; i<y*12; i++) {
                   b = b * bM;
                 }
               mP = p*iM/(1-(1/b));
               findObj('amort').innerHTML = '';
               findObj('result').innerHTML = "Your Monthly Payment: " + toCur(mP,'$') + "<br><a href='javascript:;' onclick='genHTML(mP)'>Click for Amortization Table</a>";
           }
       }
       function genHTML() {
           var p = findObj('p').value;
           var i = findObj('i').value;
           var y = findObj('y').value;
           var tHTML = '';
var tHTML = '<table width="100%"><tr><th>Month</th><th>Intrest Paid</th><th>Principal Paid</th><th>Balance</th></tr>';
           for (j=0; j<y*12; j++) {
               iP = p*i/1200;
               pP = mP-iP;
               bal= p-pP;
tHTML += '<tr class="'+((j%2!=0) ? 'style1' : 'style2')+'"><td>'+eval(j+1)+'</td><td>'+toCur(iP,'$')+'</td><td>'+toCur(pP,'$')+'</td><td>'+toCur(bal,'$')+'</td></tr>'
               p=bal;
           }
           findObj('amort').innerHTML = tHTML;
       }
       window.onload = function () { findObj('p').focus(); findObj('p').select(); }

Our unstyled calc is now ready.

Note: To change currency format to your local currency, change the function calls to function toCur eg. toCur(mP,"Rs.") for Rupees

Styling The Calculator

You may want to style the calculator to suit your requirements. The following are recommended:

  • #result is the id of the table cell that display the monthly payment display.
  • #amort is the table cell that holds the generated amortization table. Thus you can use #amort table, #amort th and #amort td to style the amortization table. Two classes .style1 and .style2 can be used to style alternate rows of the amortization table.
  • #mess styles the message available to users with javascript disabled.

View Mortgage Calculator



 

Author: Ranjan
Position: Macromedia Certified Dreamweaver MX Professional
Website: Dreamlettes
Bio:
Ranjan is a Macromedia Certified Dreamweaver MX Developer who has brainbench Master certification in Dreamweaver, Fireworks and HTML 4. He is also certified by brainbench in XHTML, Javascript, DHTML, Web Design for Accessibility and ASP. Ranjan is an associate editor at Total-Impact, besides having written for various dreamweaver and non dreamweaver resources like http://www.dmxzone.com , http://www.webthang.co.uk , http://www.maccaws.org



Date Created: 25-Oct-2007
Last Updated: 25-Oct-2007
Permalink: [link]





CATEGORY INDEX

 

 

Site Sponsors

 

Attitude e-media

 


Deliciously mobile!



Directory Templates



FireFox