The Code
function getValues() {
let loanAmount = document.getElementById('loanAmount').value;
let term = document.getElementById('term').value;
let interestRate = document.getElementById('interestRate').value;
loanAmount = parseFloat(loanAmount);
term = parseFloat(term);
interestRate = parseFloat(interestRate);
if (isNaN(loanAmount) || isNaN(term) || isNaN(interestRate) ||
loanAmount <= 0 || term <= 0 || interestRate <= 0) {
Swal.fire({
icon: 'error',
backdrop: false,
title: 'Oops',
text: 'Please enter valid values for Loan Amount, Term, and Interest Rate.'
});
return;
}
calculateMortgage(loanAmount, term, interestRate);
}
function calculateMortgage(loanAmount, term, interestRate) {// Monthly interest rate
let monthlyRate = interestRate / 100 / 12;
// Monthly payment
let monthlyPayment = (loanAmount * monthlyRate) / (1 - Math.pow(1 + monthlyRate, -term));
// Calculate payment schedule
let balance = loanAmount;
let paymentSchedule = [];
let totalInterest = 0;
for (let month = 1; month <= term; month++) {
let interest = balance * monthlyRate;
let principal = monthlyPayment - interest;
totalInterest += interest;
balance -= principal;
if (balance < 0) balance = 0;
paymentSchedule.push({
month,
payment: monthlyPayment,
principal,
interest,
totalInterest,
balance,
});
}
displayResults(paymentSchedule, monthlyPayment, loanAmount);
}
function displayResults(paymentSchedule, monthlyPayment, loanAmount) {
// Display monthly payment
document.getElementById('monthlyPayment').innerText = '$' + monthlyPayment.toFixed(2);
// Display total principal, interest, and cost
let totalPrincipal = loanAmount.toFixed(2);
let totalInterest = (monthlyPayment * paymentSchedule.length - loanAmount).toFixed(2);
let totalCost = (parseFloat(totalPrincipal) + parseFloat(totalInterest)).toFixed(2);
document.getElementById('totPrincipal').innerText = formatCurrency(totalPrincipal);
document.getElementById('totInterest').innerText = formatCurrency(totalInterest);
document.getElementById('totCost').innerText = formatCurrency(totalCost);
// Display amortization schedule
let tableBody = document.getElementById('paymentSchedule');
tableBody.innerHTML = '';
paymentSchedule.forEach(entry => {
let row = document.createElement('tr');
row.innerHTML = `<td>${entry.month}
<td>${formatCurrency(entry.payment)}
<td>${formatCurrency(entry.principal)}
<td>${formatCurrency(entry.interest)}
<td>${formatCurrency(entry.totalInterest)}
<td>${formatCurrency(entry.balance)}`;
tableBody.appendChild(row);
});
}
function formatCurrency(amount) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
The code is structured in 4 functions:
getValues()
The getValues
function retrieves the loan amount, term, and interest rate input values from the document.
It parses these values to floats and validates them to ensure they are numbers and greater than zero.
If the values are invalid, it displays an error message using SweetAlert.
Otherwise, it calls the calculateMortgage
function with the parsed values to perform the mortgage calculation.
calculateMortgage()
The calculateMortgage
function takes the loan amount, term, and interest rate as parameters.
It calculates the monthly interest rate and the monthly payment amount using the provided formula.
It then iterates over each month to calculate the interest, principal, and remaining balance, accumulating the total interest paid.
The payment details for each month are stored in an array called paymentSchedule
.
Finally, it calls the displayResults
function to show the results on the web page.
displayResults()
The displayResults
function receives the payment schedule, monthly payment, and loan amount.
It updates the HTML to display the monthly payment, total principal, total interest, and total cost.
It also generates an amortization schedule by creating table rows for each entry in the payment schedule array.
Each row displays the month, payment, principal, interest, total interest, and balance.
This function ensures that the calculated mortgage details are presented to the user in a readable format.
formatCurrency()
The formatCurrency
function takes a numeric amount and formats it as a currency string in USD.
It uses the Intl.NumberFormat
object to format the number according to the en-US locale and USD currency style.
This function is used to ensure that all monetary values displayed on the web page are formatted consistently and clearly.