70 lines
2.9 KiB
JavaScript
70 lines
2.9 KiB
JavaScript
document.addEventListener('DOMContentLoaded', function () {
|
|
// DOM Elements
|
|
const loanAmountInput = document.getElementById('loanAmount');
|
|
const interestRateInput = document.getElementById('interestRate');
|
|
const loanTermInput = document.getElementById('loanTerm');
|
|
|
|
const loanAmountLabel = document.getElementById('loanAmountLabel');
|
|
const interestRateLabel = document.getElementById('interestRateLabel');
|
|
const loanTermLabel = document.getElementById('loanTermLabel');
|
|
|
|
const monthlyPaymentOutput = document.getElementById('monthlyPayment');
|
|
const totalInterestOutput = document.getElementById('totalInterest');
|
|
const totalPaidOutput = document.getElementById('totalPaid');
|
|
|
|
// Format number as currency
|
|
const currencyFormatter = new Intl.NumberFormat('en-US', {
|
|
style: 'currency',
|
|
currency: 'USD',
|
|
});
|
|
|
|
function calculateLoan() {
|
|
const principal = parseFloat(loanAmountInput.value);
|
|
const annualInterestRate = parseFloat(interestRateInput.value);
|
|
const years = parseInt(loanTermInput.value, 10);
|
|
|
|
// Update labels
|
|
loanAmountLabel.textContent = currencyFormatter.format(principal).replace('.00', '');
|
|
interestRateLabel.textContent = `${annualInterestRate.toFixed(1)}%`;
|
|
loanTermLabel.textContent = `${years} ${years > 1 ? 'Years' : 'Year'}`;
|
|
|
|
// Calculation logic
|
|
if (principal > 0 && annualInterestRate > 0 && years > 0) {
|
|
const monthlyInterestRate = annualInterestRate / 100 / 12;
|
|
const numberOfPayments = years * 12;
|
|
|
|
const monthlyPayment = principal * (monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments)) / (Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1);
|
|
|
|
if (isFinite(monthlyPayment)) {
|
|
const totalPaid = monthlyPayment * numberOfPayments;
|
|
const totalInterest = totalPaid - principal;
|
|
|
|
// Update UI
|
|
monthlyPaymentOutput.textContent = currencyFormatter.format(monthlyPayment);
|
|
totalInterestOutput.textContent = currencyFormatter.format(totalInterest);
|
|
totalPaidOutput.textContent = currencyFormatter.format(totalPaid);
|
|
} else {
|
|
// Handle case where interest is 0 or other invalid scenarios
|
|
resetResults();
|
|
}
|
|
} else {
|
|
resetResults();
|
|
}
|
|
}
|
|
|
|
function resetResults() {
|
|
monthlyPaymentOutput.textContent = currencyFormatter.format(0);
|
|
totalInterestOutput.textContent = currencyFormatter.format(0);
|
|
totalPaidOutput.textContent = currencyFormatter.format(0);
|
|
}
|
|
|
|
|
|
// Event Listeners
|
|
loanAmountInput.addEventListener('input', calculateLoan);
|
|
interestRateInput.addEventListener('input', calculateLoan);
|
|
loanTermInput.addEventListener('input', calculateLoan);
|
|
|
|
// Initial calculation on page load
|
|
calculateLoan();
|
|
});
|