40 lines
1.7 KiB
JavaScript
40 lines
1.7 KiB
JavaScript
|
|
document.addEventListener('DOMContentLoaded', function () {
|
|
const loanAmountInput = document.getElementById('loanAmount');
|
|
const interestRateInput = document.getElementById('interestRate');
|
|
const loanTermInput = document.getElementById('loanTerm');
|
|
|
|
const monthlyPaymentDisplay = document.getElementById('monthlyPayment');
|
|
const totalInterestDisplay = document.getElementById('totalInterest');
|
|
|
|
function calculateLoan() {
|
|
const principal = parseFloat(loanAmountInput.value) || 0;
|
|
const annualInterestRate = parseFloat(interestRateInput.value) || 0;
|
|
const years = parseInt(loanTermInput.value) || 0;
|
|
|
|
if (principal > 0 && annualInterestRate > 0 && years > 0) {
|
|
const monthlyInterestRate = annualInterestRate / 100 / 12;
|
|
const numberOfPayments = years * 12;
|
|
|
|
const numerator = monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments);
|
|
const denominator = Math.pow(1 + monthlyInterestRate, numberOfPayments) - 1;
|
|
const monthlyPayment = principal * (numerator / denominator);
|
|
|
|
const totalPaid = monthlyPayment * numberOfPayments;
|
|
const totalInterest = totalPaid - principal;
|
|
|
|
monthlyPaymentDisplay.textContent = `$${monthlyPayment.toFixed(2)}`;
|
|
totalInterestDisplay.textContent = `$${totalInterest.toFixed(2)}`;
|
|
} else {
|
|
monthlyPaymentDisplay.textContent = '$0.00';
|
|
totalInterestDisplay.textContent = '$0.00';
|
|
}
|
|
}
|
|
|
|
[loanAmountInput, interestRateInput, loanTermInput].forEach(input => {
|
|
input.addEventListener('input', calculateLoan);
|
|
});
|
|
|
|
calculateLoan(); // Initial calculation
|
|
});
|