﻿ Here's a simple JavaScript code for an amortizing loan calculator - ITS UP 2 U - Information

## Here's a simple JavaScript code for an amortizing loan calculator

``````function calculateLoan() {
var principal = document.getElementById("principal").value;
var interestRate = document.getElementById("interestRate").value;
var term = document.getElementById("term").value;

var monthlyRate = interestRate/1200;
var monthlyPayment = (principal * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -term));

var balance = principal;
var table = "<table><tr><th>Month</th><th>Payment</th><th>Principal</th><th>Interest</th><th>Balance</th></tr>";

for (var i = 1; i <= term; i++) {
var interest = balance * monthlyRate;
var principalPaid = monthlyPayment - interest;
balance -= principalPaid;

table += "<tr><td>" + i + "</td><td>\$" + monthlyPayment.toFixed(2) + "</td><td>\$" + principalPaid.toFixed(2) + "</td><td>\$" + interest.toFixed(2) + "</td><td>\$" + balance.toFixed(2) + "</td></tr>";
}

table += "</table>";
document.getElementById("output").innerHTML = table;
}``````

This code takes input values for the loan principal, interest rate, and term from the user, and calculates the monthly payment, principal paid, interest paid, and loan balance for each month using a for loop. The output is displayed in an HTML table using the `innerHTML` property. The `toFixed()` method is used to format the output to two decimal places.

You can use this code in an HTML document with a form that has input fields for the loan details and a button that calls the `calculateLoan()` function. For example:

``````<form>
<label for="principal">Loan Amount:</label>
<input type="text" id="principal" name="principal"><br>

<label for="interestRate">Interest Rate:</label>
<input type="text" id="interestRate" name="interestRate"><br>

<label for="term">Loan Term (months):</label>
<input type="text" id="term" name="term"><br>

<button type="button" onclick="calculateLoan()">Calculate</button>
</form>

<div id="output"></div>``````

This code will display the loan calculator form and the output table in the HTML document.

Click to listen highlighted text!