MonthlyPayment Example -- Source Code
HTML Page -- index.htm
<!DOCTYPE html>
<!-- MonthlyPayment Example
Source code file: index.htm
Compute monthly payment for a loan, using
principal, interest rate, and term of loan
in years. -->
<html lang="em">
<head>
<title>MonthlyPayment Example</title>
<script src="mp2.js"></script>
</head>
<body>
<h1>Monthly Payment Example</h1>
<div id="ctrls">
<input type="text" id="princ">
<label for="princ">Principal</label><br><br>
<input type="text" id="interest">
<label for="interest">Interest</label><br><br>
<input type="text" id="term">
<label for="term">Term in Years</label><br><br>
<hr><br>
<button id="btn">
Compute Monthly Payment
</button><br><br>
<input type="text" id="monthly">
<label for="monthly">Monthly Payment</label>
</div>
</body>
</html>
Script Page -- mp2.js
// Function to compute monthly payment,
// with inputs principal, interest rate,
// term of loan in years.
function computeMP(p, r, n) {
var m = (p * r / 1200.0) /
(1 - (1.0 + r / 1200.0) ** (-12.0 * n));
return m;
}
// Click event handler for button
function onClickMethod( ) {
var p = parseFloat(
document.getElementById("princ").value);
var r = parseFloat(
document.getElementById("interest").value);
var n = parseFloat(
document.getElementById("term").value);
var m = computeMP(p, r, n);
var output = document.getElementById("monthly");
// Round off m to two digits after the decimal point.
var roundedM = Math.round(m * 100) / 100;
// valueOf changes number to string.
output.value = roundedM.valueOf( );
}
// Initialization function that adds click
// event handler to button
function init( ) {
var button = document.getElementById("btn");
button.addEventListener("click", onClickMethod);
}
// Execute init method when window loads.
window.addEventListener("load", init);