How is a Mortgage Calculated? – Comprehensive Guide & Calculator
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
background-color: #f8f9fa;
color: #333;
margin: 0;
padding: 0;
}
.container {
max-width: 1000px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
header {
background-color: #004a99;
color: #fff;
padding: 20px 0;
text-align: center;
border-radius: 8px 8px 0 0;
}
header h1 {
margin: 0;
font-size: 2.5em;
}
main {
padding: 20px;
}
h1, h2, h3 {
color: #004a99;
}
h1 {
font-size: 2em;
margin-bottom: 15px;
}
h2 {
font-size: 1.7em;
margin-top: 30px;
margin-bottom: 15px;
border-bottom: 2px solid #eee;
padding-bottom: 5px;
}
h3 {
font-size: 1.4em;
margin-top: 20px;
margin-bottom: 10px;
}
.loan-calc-container {
background-color: #e9ecef;
padding: 25px;
border-radius: 8px;
margin-bottom: 30px;
box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);
}
.input-group {
margin-bottom: 20px;
text-align: left;
}
.input-group label {
display: block;
margin-bottom: 8px;
font-weight: bold;
color: #004a99;
}
.input-group input[type="number"],
.input-group input[type="text"],
.input-group select {
width: calc(100% – 22px);
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1em;
box-sizing: border-box;
}
.input-group input[type="number"]:focus,
.input-group input[type="text"]:focus,
.input-group select:focus {
border-color: #004a99;
outline: none;
box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2);
}
.input-group .helper-text {
font-size: 0.85em;
color: #666;
margin-top: 5px;
display: block;
}
.error-message {
color: #dc3545;
font-size: 0.9em;
margin-top: 5px;
display: none; /* Hidden by default */
}
.button-group {
text-align: center;
margin-top: 25px;
}
.btn {
padding: 10px 20px;
font-size: 1em;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
transition: background-color 0.3s ease;
}
.btn-primary {
background-color: #004a99;
color: #fff;
}
.btn-primary:hover {
background-color: #003b7a;
}
.btn-secondary {
background-color: #6c757d;
color: #fff;
}
.btn-secondary:hover {
background-color: #5a6268;
}
.btn-danger {
background-color: #dc3545;
color: #fff;
}
.btn-danger:hover {
background-color: #c82333;
}
#results {
background-color: #ffffff;
padding: 25px;
border-radius: 8px;
margin-top: 30px;
box-shadow: 0 1px 5px rgba(0,0,0,0.1);
border: 1px solid #dee2e6;
}
#results h3 {
margin-top: 0;
color: #004a99;
text-align: center;
margin-bottom: 20px;
}
.result-item {
margin-bottom: 15px;
font-size: 1.1em;
display: flex;
justify-content: space-between;
align-items: center;
}
.result-item span:first-child {
font-weight: bold;
color: #555;
}
.result-item span:last-child {
font-weight: bold;
color: #28a745;
font-size: 1.2em;
}
.primary-result {
background-color: #28a745;
color: #fff;
padding: 15px;
border-radius: 5px;
text-align: center;
font-size: 1.5em;
font-weight: bold;
margin-top: 10px;
margin-bottom: 20px;
box-shadow: 0 2px 5px rgba(40, 167, 69, 0.5);
}
.formula-explanation {
font-size: 0.95em;
color: #555;
margin-top: 20px;
padding: 15px;
background-color: #f1f1f1;
border-left: 4px solid #004a99;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
margin-bottom: 30px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #004a99;
color: #fff;
font-weight: bold;
}
td {
background-color: #f9f9f9;
}
tr:nth-child(even) td {
background-color: #f1f1f1;
}
caption {
font-size: 1.1em;
font-weight: bold;
color: #333;
margin-bottom: 10px;
caption-side: top;
text-align: left;
}
canvas {
display: block;
margin: 20px auto;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 1px 5px rgba(0,0,0,0.1);
}
.chart-legend {
text-align: center;
margin-top: 10px;
font-size: 0.9em;
color: #555;
}
.chart-legend span {
margin: 0 10px;
}
.chart-legend .legend-color {
display: inline-block;
width: 12px;
height: 12px;
margin-right: 5px;
border-radius: 3px;
vertical-align: middle;
}
.legend-principal { background-color: #007bff; }
.legend-interest { background-color: #ffc107; }
section {
margin-top: 30px;
padding-top: 20px;
}
.faq-list, .related-links {
list-style: none;
padding: 0;
}
.faq-item, .related-link-item {
margin-bottom: 15px;
padding: 15px;
background-color: #f8f9fa;
border-radius: 5px;
border-left: 4px solid #004a99;
}
.faq-item strong, .related-link-item strong {
color: #004a99;
display: block;
margin-bottom: 5px;
}
.related-links a {
color: #004a99;
text-decoration: none;
font-weight: bold;
}
.related-links a:hover {
text-decoration: underline;
}
.internal-link {
color: #004a99;
font-weight: bold;
text-decoration: none;
}
.internal-link:hover {
text-decoration: underline;
}
footer {
text-align: center;
margin-top: 40px;
padding: 20px;
font-size: 0.9em;
color: #666;
border-top: 1px solid #eee;
}
Understanding How a Mortgage is Calculated
Mortgage Payment Calculator
Your Mortgage Payment Breakdown
$0.00
Principal & Interest (P&I)
$0.00
Total Paid Over Loan Term
$0.00
Total Interest Paid
$0.00
How is a mortgage calculated? The standard formula for a fixed-rate mortgage payment (P&I) is: M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Where:
M = Monthly Payment
P = Principal Loan Amount
i = Monthly Interest Rate (Annual Rate / 12)
n = Total Number of Payments (Loan Term in Years * 12)
Amortization Schedule
Monthly Breakdown of Your Mortgage
| Month |
Starting Balance |
Payment (P&I) |
Principal Paid |
Interest Paid |
Ending Balance |
Loan Breakdown Chart
Principal Interest
What is Mortgage Calculation?
Understanding how is a mortgage calculated is fundamental for any aspiring or existing homeowner. A mortgage calculation determines the periodic payment required to repay a loan over a specified period, covering both the principal borrowed and the interest charged. It's the cornerstone of homeownership affordability and financial planning.
Who should use it? Anyone looking to buy a property with a loan, homeowners considering refinancing, or individuals wanting to understand the long-term cost of their mortgage. It's also a vital tool for financial advisors helping clients assess affordability.
Common misconceptions: Many believe the monthly payment only covers the principal. In reality, a significant portion of early mortgage payments goes towards interest. Another misconception is that the interest rate is the only factor; loan term and principal amount have equally significant impacts on the total cost and monthly burden.
Mortgage Calculation Formula and Mathematical Explanation
The standard method for calculating a fixed-rate mortgage payment is based on the amortization formula. This formula ensures that each payment gradually reduces the principal balance while covering the interest accrued for that period.
The core formula used to determine the monthly payment (M) is:
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
Let's break down each variable:
Mortgage Calculation Variables
| Variable |
Meaning |
Unit |
Typical Range |
| M |
Monthly Payment (Principal & Interest) |
Currency (e.g., $) |
Varies greatly based on P, i, n |
| P |
Principal Loan Amount |
Currency (e.g., $) |
$10,000 – $1,000,000+ |
| i |
Monthly Interest Rate |
Decimal (e.g., 0.05 / 12) |
(Annual Rate / 12), typically 0.002 to 0.083 (0.25% to 10%) |
| n |
Total Number of Payments |
Count |
180 (15 years), 240 (20 years), 360 (30 years) |
Step-by-step derivation:
- Calculate the monthly interest rate (i): Divide the annual interest rate by 12. For example, a 5% annual rate becomes 0.05 / 12 = 0.00416667.
- Calculate the total number of payments (n): Multiply the loan term in years by 12. A 30-year loan has 30 * 12 = 360 payments.
- Calculate the numerator: P * [ i * (1 + i)^n ]. This part represents the interest portion adjusted for the compounding effect.
- Calculate the denominator: [ (1 + i)^n – 1]. This normalizes the payment to ensure the principal is fully repaid over 'n' periods.
- Divide numerator by denominator: M = Numerator / Denominator. This gives you the fixed monthly payment.
This calculation forms the basis of amortization schedules, which detail how each payment is allocated between principal and interest over the life of the loan.
Practical Examples of Mortgage Calculation
Let's illustrate how different scenarios affect the mortgage payment. The core principle of how is a mortgage calculated remains the same, but the inputs dramatically change the output.
Example 1: Standard Home Purchase
Scenario: A buyer purchases a home with a loan of $300,000 at an annual interest rate of 5% for a term of 30 years.
- Principal (P): $300,000
- Annual Interest Rate: 5%
- Loan Term: 30 years
Using the calculator or formula:
- Monthly Interest Rate (i): 5% / 12 = 0.00416667
- Number of Payments (n): 30 years * 12 = 360
- Monthly P&I Payment (M): Approximately $1,610.46
- Total Paid Over Loan Term: $1,610.46 * 360 = $579,765.60
- Total Interest Paid: $579,765.60 – $300,000 = $279,765.60
Interpretation: The buyer will pay roughly $1,610 per month for principal and interest. Over 30 years, they will pay back the original $300,000 plus nearly $280,000 in interest.
Example 2: Shorter Loan Term
Scenario: The same buyer decides to opt for a shorter 15-year term for the same $300,000 loan at 5% interest.
- Principal (P): $300,000
- Annual Interest Rate: 5%
- Loan Term: 15 years
Using the calculator or formula:
- Monthly Interest Rate (i): 5% / 12 = 0.00416667
- Number of Payments (n): 15 years * 12 = 180
- Monthly P&I Payment (M): Approximately $2,121.31
- Total Paid Over Loan Term: $2,121.31 * 180 = $381,835.80
- Total Interest Paid: $381,835.80 – $300,000 = $81,835.80
Interpretation: Although the monthly payment increases significantly (by about $511), the total interest paid is drastically reduced by over $198,000. This highlights the power of shortening the loan term.
How to Use This Mortgage Calculation Tool
Our mortgage calculator simplifies the complex process of determining your potential monthly payments. Follow these steps:
- Enter Loan Amount: Input the total amount you intend to borrow for the property.
- Input Annual Interest Rate: Enter the current annual interest rate offered by lenders. Be precise, as even small changes impact payments.
- Select Loan Term: Choose the desired duration for your mortgage repayment (e.g., 15, 20, 30 years).
- Click 'Calculate Monthly Payment': The tool will instantly display your estimated Principal & Interest (P&I) payment.
Reading the Results:
- Primary Result (Monthly P&I): This is the core payment for loan repayment. Note that this excludes property taxes, homeowners insurance (often called PITI), and potential PMI.
- Total Paid Over Loan Term: Shows the cumulative amount you'll pay back, including principal and all interest.
- Total Interest Paid: Reveals the total cost of borrowing over the entire loan period.
Decision-Making Guidance: Use these results to gauge affordability. If the calculated P&I payment is too high, consider a lower purchase price, a larger down payment, a longer loan term, or seeking a lower interest rate. Compare different scenarios by adjusting inputs.
Key Factors That Affect Mortgage Calculation Results
Several elements significantly influence how is a mortgage calculated and, consequently, your monthly payments and the total cost of borrowing. Understanding these is crucial for financial planning:
-
Interest Rate: The most direct influence. A higher rate means a higher monthly payment and substantially more interest paid over time. Lenders determine rates based on credit score, market conditions, loan type, and loan-to-value ratio. Understanding the impact of mortgage rates is vital.
-
Principal Loan Amount: The larger the amount borrowed, the higher the monthly payment and total interest. This is directly tied to the home's price and the size of your down payment. A larger down payment reduces the principal, lowering both payment and interest costs.
-
Loan Term (Amortization Period): A longer term results in lower monthly payments but significantly increases the total interest paid over the life of the loan. Conversely, a shorter term yields higher monthly payments but saves substantially on interest. Explore different loan options to find the best balance.
-
Loan-to-Value (LTV) Ratio: This is the ratio of the loan amount to the home's appraised value. A high LTV (meaning a small down payment) often correlates with higher interest rates and may require Private Mortgage Insurance (PMI).
-
Fees and Closing Costs: While not directly part of the P&I calculation, various lender fees (origination, appraisal, title insurance, etc.) add to the upfront cost of obtaining the mortgage. These should be factored into your overall budget.
-
Property Taxes and Homeowners Insurance: These are often escrowed and added to your monthly mortgage payment (forming PITI – Principal, Interest, Taxes, Insurance). Fluctuations in these costs will change your total housing expense, even if the P&I remains fixed.
- Inflation and Economic Conditions: While not directly in the P&I formula, inflation impacts the purchasing power of future payments and can influence interest rate trends set by central banks. Economic stability affects lender confidence and borrowing costs.
Frequently Asked Questions (FAQ)
Q1: Does the calculator include property taxes and insurance?
A: No, this calculator specifically computes the Principal and Interest (P&I) portion of your mortgage payment. Property taxes, homeowners insurance, and potentially Private Mortgage Insurance (PMI) are typically added to this amount to determine your total monthly housing expense (PITI).
Q2: How does a credit score affect my mortgage calculation?
A: Your credit score heavily influences the interest rate you'll be offered. A higher credit score generally leads to a lower interest rate, significantly reducing your monthly payment and the total interest paid over the loan's life. This calculator uses a set rate, but in reality, your score dictates that rate.
Q3: What is the difference between an amortization schedule and a mortgage payment calculation?
A: The mortgage payment calculation gives you the fixed periodic payment (P&I). The amortization schedule breaks down how each of those payments is applied over time, showing the decreasing principal balance and the corresponding interest paid each month.
Q4: Can I use this calculator for adjustable-rate mortgages (ARMs)?
A: This calculator is designed for fixed-rate mortgages. ARMs have interest rates that can change periodically after an initial fixed period, making their future payments unpredictable and requiring different calculation methods.
Q5: What happens if I make extra payments?
A: Making extra payments, especially towards the principal, can significantly shorten your loan term and reduce the total interest paid. Some lenders allow extra payments without penalty; always verify this.
Q6: What is PMI and do I need to include it?
A: Private Mortgage Insurance (PMI) is required by lenders if your down payment is less than 20% of the home's purchase price. It protects the lender. You would typically add the cost of PMI to the calculated P&I payment for your total housing expense.
Q7: How do points affect my mortgage calculation?
A: Points are fees paid directly to the lender at closing in exchange for a reduced interest rate. Paying points upfront can lower your interest rate (i), thereby reducing your monthly payment (M) and total interest paid over the loan's life. This calculator doesn't directly model points but assumes a given rate.
Q8: Is the total interest paid the only cost of borrowing?
A: No. While total interest is a major cost, you also need to factor in closing costs, potential PMI, property taxes, homeowners insurance, and maintenance costs when assessing the true cost of homeownership.
Related Tools and Internal Resources
var principalInput = document.getElementById("loanAmount");
var annualRateInput = document.getElementById("annualInterestRate");
var loanTermInput = document.getElementById("loanTermYears");
var monthlyPaymentResultEl = document.getElementById("monthlyPaymentResult");
var pAndIResultEl = document.getElementById("pAndIResult");
var totalPaidResultEl = document.getElementById("totalPaidResult");
var totalInterestResultEl = document.getElementById("totalInterestResult");
var amortizationTableBody = document.getElementById("amortizationTable").getElementsByTagName('tbody')[0];
var chartCanvas = document.getElementById("loanChart");
var chartContext = chartCanvas.getContext("2d");
var chartInstance = null;
var loanAmountErrorEl = document.getElementById("loanAmountError");
var annualInterestRateErrorEl = document.getElementById("annualInterestRateError");
var loanTermYearsErrorEl = document.getElementById("loanTermYearsError");
function formatCurrency(amount) {
return "$" + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
function formatPercent(rate) {
return rate.toFixed(2) + "%";
}
function showError(element, message) {
element.innerText = message;
element.style.display = 'block';
}
function clearError(element) {
element.innerText = ";
element.style.display = 'none';
}
function validateInputs() {
var valid = true;
var loanAmount = parseFloat(principalInput.value);
var annualInterestRate = parseFloat(annualRateInput.value);
var loanTermYears = parseInt(loanTermInput.value);
if (isNaN(loanAmount) || loanAmount <= 0) {
showError(loanAmountErrorEl, "Please enter a valid loan amount.");
valid = false;
} else {
clearError(loanAmountErrorEl);
}
if (isNaN(annualInterestRate) || annualInterestRate 100) {
showError(annualInterestRateErrorEl, "Please enter a valid annual interest rate between 0% and 100%.");
valid = false;
} else {
clearError(annualInterestRateErrorEl);
}
if (isNaN(loanTermYears) || loanTermYears 0) {
monthlyPayment = principal * (monthlyRate * Math.pow(1 + monthlyRate, numberOfPayments)) / (Math.pow(1 + monthlyRate, numberOfPayments) – 1);
} else {
monthlyPayment = principal / numberOfPayments;
}
totalPaid = monthlyPayment * numberOfPayments;
totalInterest = totalPaid – principal;
monthlyPaymentResultEl.innerText = formatCurrency(monthlyPayment);
pAndIResultEl.innerText = formatCurrency(monthlyPayment);
totalPaidResultEl.innerText = formatCurrency(totalPaid);
totalInterestResultEl.innerText = formatCurrency(totalInterest);
// Generate Amortization Schedule
var currentBalance = principal;
var cumulativeInterest = 0;
var cumulativePrincipal = 0;
for (var i = 0; i < numberOfPayments; i++) {
var interestPayment = currentBalance * monthlyRate;
var principalPayment = monthlyPayment – interestPayment;
// Adjust last payment to ensure balance is exactly zero
if (i === numberOfPayments – 1) {
principalPayment = currentBalance;
monthlyPayment = interestPayment + principalPayment;
totalPaid = (monthlyPayment * i) + monthlyPayment;
totalInterest = totalPaid – principal;
pAndIResultEl.innerText = formatCurrency(monthlyPayment);
totalPaidResultEl.innerText = formatCurrency(totalPaid);
totalInterestResultEl.innerText = formatCurrency(totalInterest);
}
currentBalance -= principalPayment;
if (currentBalance < 0) currentBalance = 0; // Prevent negative balance due to rounding
amortizationData.push({
month: i + 1,
startBalance: principal – cumulativePrincipal,
payment: monthlyPayment,
principalPaid: principalPayment,
interestPaid: interestPayment,
endBalance: currentBalance
});
cumulativeInterest += interestPayment;
cumulativePrincipal += principalPayment;
}
renderAmortizationTable(amortizationData);
renderChart(amortizationData);
}
function renderAmortizationTable(data) {
amortizationTableBody.innerHTML = ''; // Clear previous rows
var maxRows = 12; // Display max 12 rows for brevity
var rowsToShow = Math.min(data.length, maxRows);
for (var i = 0; i maxRows) {
var row = amortizationTableBody.insertRow();
var cell = row.insertCell(0);
cell.colSpan = 6;
cell.innerText = "… showing first " + maxRows + " of " + data.length + " months.";
cell.style.textAlign = "center";
cell.style.fontStyle = "italic";
}
}
function renderChart(data) {
if (chartInstance) {
chartInstance.destroy(); // Destroy previous chart instance
}
var totalMonths = data.length;
var principalPaidArray = data.map(function(item) { return item.principalPaid; });
var interestPaidArray = data.map(function(item) { return item.interestPaid; });
var labels = data.map(function(item, index) { return index < 12 ? (index + 1).toString() : ''; }).filter(String); // Show labels for first 12 months
var principalSum = principalPaidArray.reduce(function(sum, current) { return sum + current; }, 0);
var interestSum = interestPaidArray.reduce(function(sum, current) { return sum + current; }, 0);
chartCanvas.height = 300; // Adjust canvas height
chartInstance = new Chart(chartContext, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Principal Paid',
data: principalPaidArray.slice(0, 12), // Show first 12 bars
backgroundColor: 'rgba(0, 74, 153, 0.7)', // #004a99
borderColor: 'rgba(0, 74, 153, 1)',
borderWidth: 1
}, {
label: 'Interest Paid',
data: interestPaidArray.slice(0, 12), // Show first 12 bars
backgroundColor: 'rgba(255, 193, 7, 0.7)', // #ffc107 (yellow)
borderColor: 'rgba(255, 193, 7, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'Amount ($)'
}
},
x: {
title: {
display: true,
text: 'Month (First 12)'
}
}
},
plugins: {
legend: {
display: false // Legend handled by separate div
},
tooltip: {
callbacks: {
label: function(context) {
var label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += formatCurrency(context.parsed.y);
}
return label;
}
}
}
}
}
});
}
function resetCalculator() {
principalInput.value = "300000";
annualRateInput.value = "5";
loanTermInput.value = "30";
clearError(loanAmountErrorEl);
clearError(annualInterestRateErrorEl);
clearError(loanTermYearsErrorEl);
calculateMortgage();
}
function copyResults() {
var principal = parseFloat(principalInput.value);
var annualRate = parseFloat(annualRateInput.value);
var loanTermYears = parseInt(loanTermInput.value);
var monthlyPayment = parseFloat(monthlyPaymentResultEl.innerText.replace(/[^0-9.-]+/g,""));
var totalPaid = parseFloat(totalPaidResultEl.innerText.replace(/[^0-9.-]+/g,""));
var totalInterest = parseFloat(totalInterestResultEl.innerText.replace(/[^0-9.-]+/g,""));
var textToCopy = "— Mortgage Calculation Summary —\n\n";
textToCopy += "Assumptions:\n";
textToCopy += "- Loan Amount: " + formatCurrency(principal) + "\n";
textToCopy += "- Annual Interest Rate: " + formatPercent(annualRate) + "\n";
textToCopy += "- Loan Term: " + loanTermYears + " years\n\n";
textToCopy += "Results:\n";
textToCopy += "- Monthly Payment (P&I): " + formatCurrency(monthlyPayment) + "\n";
textToCopy += "- Total Paid Over Loan Term: " + formatCurrency(totalPaid) + "\n";
textToCopy += "- Total Interest Paid: " + formatCurrency(totalInterest) + "\n";
// Try to copy using the modern Clipboard API first
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(textToCopy).then(function() {
alert("Results copied to clipboard!");
}).catch(function(err) {
console.error("Clipboard API failed: ", err);
// Fallback for older browsers or if clipboard API fails
copyToClipboardFallback(textToCopy);
});
} else {
// Fallback for older browsers
copyToClipboardFallback(textToCopy);
}
}
function copyToClipboardFallback(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
// Avoid scrolling to bottom
textArea.style.position = "fixed";
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.width = "2em";
textArea.style.height = "2em";
textArea.style.padding = "0";
textArea.style.border = "none";
textArea.style.outline = "none";
textArea.style.boxShadow = "none";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Fallback: Copying text command was ' + msg);
alert('Results copied to clipboard!');
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
alert('Failed to copy results. Please copy manually.');
}
document.body.removeChild(textArea);
}
// Initial calculation on page load
window.onload = function() {
calculateMortgage();
};
// Re-calculate on input change
var inputs = document.querySelectorAll(".loan-calc-container input, .loan-calc-container select");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("input", calculateMortgage);
}
// Add Chart.js library for charting
var chartScript = document.createElement('script');
chartScript.src = 'https://cdn.jsdelivr.net/npm/chart.js';
chartScript.onload = function() {
console.log('Chart.js loaded.');
// Ensure calculateMortgage runs after Chart.js is loaded if it hasn't already
if(document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', calculateMortgage);
} else {
calculateMortgage();
}
};
document.head.appendChild(chartScript);