Wednesday, October 6, 2010

JavaScript Payment Calculator

Here is an exciting JavaScript example for CS171. The code is provided below. There are two files for the code if you're planning on copying this as was done in class, no5.html and no5.js.

no5.html

<html>
<head>
<title>Interest Calculator</title>

<script type="text/javascript" src="no5.js"></script>

<style>
#userInput {
display: block;
margin-bottom: 30px;
width: 450px;
}
#data {
width: 450px;
}
#data th, #data td{
border:#000 1px solid;
}
#data td {
text-align: right;
}
.textField {
display: block;
text-align: right;
}
#calculate {
float: right;
display: block;
}
</style>

</head>

<body>

<div id="userInput">
<div class="textField">Annual Interest Rate: <input id="apr" value=".18" /></div>
<div class="textField">Beginning Balance: <input id="startBalance" value="5000" /></div>
<div class="textField">Payment: <input id="payment" value="85" /></div>
<div class="textField">Number of periods per year: <input id="numPayments" value="12" /></div>
<div class="textField">Number of years: <input id="years" value="1" /></div>
<input type="submit" Value= "Caclulate" id="calculate" onClick="resetTable(); calculate(document.getElementById('startBalance').value, document.getElementById('apr').value, document.getElementById('payment').value, document.getElementById('numPayments').value,1,document.getElementById('years').value*document.getElementById('numPayments').value);" />
</div>
<div id="userOutput">
<table id="data">
<tr>
<th>Period Number</th>
<th>Payment Amount</th>
<th>Interest Paid</th>
<th>Principle Paid</th>
<th>Remaining Balance</th>
</tr>
</table>
</div>

</body>

no5.js

function calculate(balance, apr, pay, nper, currentPeriod, n) {
if ((apr!="")&&(balance!="")&&(pay!="")&&(nper!="")){
if (balance > 0) {
interest = balance * apr/nper;
interest = Math.round(100 * interest)/100;
if (balance < (pay-interest) ) {
pay=balance + interest;
pay=Math.round(pay*100)/100;
}
principle = pay - interest;
principle = Math.round(100 * principle)/100;
newBalance = balance - principle;
newBalance = Math.round(100 * newBalance)/100;
htmlString = '' + currentPeriod + '' + pay + '' + interest + '' + principle + '' + newBalance + ''
myelement = document.getElementById("data");
myelement.innerHTML=myelement.innerHTML + htmlString + "\n";
if (n-currentPeriod>0)
calculate(newBalance, apr, pay, nper, currentPeriod+1, n);
}
}
return true;
}
function resetTable() {
document.getElementById("data").innerHTML='Period NumberPayment AmountInterest PaidPrinciple PaidRemaining Balance';
}