Calculate your estimated monthly mortgage payments for a $300,000 loan. This tool helps you understand the impact of interest rates and loan terms on your payments.
Mortgage Payment Calculator
Enter the total amount you wish to borrow.
Enter the annual interest rate for your mortgage (e.g., 6.5 for 6.5%).
15 Years
20 Years
25 Years
30 Years
40 Years
Select the duration of your mortgage.
Your Estimated Monthly Payment
$0.00
Principal & Interest: $0.00
Total Interest Paid: $0.00
Total Amount Paid: $0.00
This calculation is based on the standard Amortization Formula (M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]), where P is the principal loan amount, i is the monthly interest rate, and n is the total number of payments. This estimate does not include property taxes, homeowner's insurance, or Private Mortgage Insurance (PMI), which can significantly increase your total monthly housing cost.
Loan Amortization Breakdown
Chart showing the breakdown of principal and interest paid over the life of the loan.
Loan Amortization Schedule (First 5 Payments & Last Payment)
Payment #
Payment Amount
Principal Paid
Interest Paid
Remaining Balance
What is a 300,000 Mortgage Calculator?
A 300,000 mortgage calculator is a specialized financial tool designed to estimate the monthly mortgage payments for a loan amount of $300,000. It helps potential homeowners and refinancers understand how different variables, such as the annual interest rate and the loan term (in years), impact their overall monthly outlay and the total cost of the loan over its lifespan. This specific calculator focuses on the principal and interest (P&I) portion of the mortgage payment, which is a core component of any home loan repayment. Understanding these figures is crucial for budgeting and making informed decisions about homeownership, especially when dealing with a significant loan amount like $300,000.
Who should use it? Anyone considering purchasing a home with a purchase price that would require a $300,000 mortgage, or those looking to refinance an existing loan to a new balance of approximately $300,000. This includes first-time homebuyers, individuals upgrading their homes, or those seeking to leverage their home equity. It's also useful for financial advisors and real estate professionals who need to provide quick estimates to clients.
Common misconceptions about mortgage calculators include believing they provide the final, all-inclusive monthly housing cost. Many users forget that the calculated P&I is only part of the payment. Escrow payments for property taxes and homeowner's insurance, along with potential Private Mortgage Insurance (PMI) for loans with less than 20% down, are typically added to the monthly bill. Another misconception is that the quoted interest rate is fixed for the entire loan term; adjustable-rate mortgages (ARMs) can see rates change over time.
300,000 Mortgage Calculator Formula and Mathematical Explanation
The 300,000 mortgage calculator uses the standard annuity formula to determine the fixed monthly payment (M) for a mortgage. This formula ensures that over the life of the loan, the borrower pays off both the principal amount borrowed and the accumulated interest through equal installments.
Convert Annual Rate to Monthly Rate: The annual interest rate (r) is divided by 12 to get the monthly interest rate (i). So, i = Annual Rate / 12 / 100. For example, a 6.5% annual rate becomes 0.065 / 12.
Calculate Total Number of Payments: The loan term in years is multiplied by 12 to get the total number of monthly payments (n). For a 30-year loan, n = 30 * 12 = 360.
Apply the Annuity Formula: Substitute P, i, and n into the formula above to calculate M. The formula essentially balances the present value of the loan (P) with the future value of all payments (M) considering the time value of money (interest rate i).
This calculation provides the fixed P&I payment required to fully amortize the loan by the end of its term.
Practical Examples (Real-World Use Cases)
Example 1: First-Time Homebuyer
Sarah is buying her first home and needs a $300,000 mortgage. She has secured a 30-year fixed-rate mortgage with an annual interest rate of 6.5%. She wants to know her estimated monthly principal and interest payment.
Inputs: Loan Amount (P) = $300,000, Annual Interest Rate = 6.5%, Loan Term = 30 Years
Outputs: Estimated Monthly P&I Payment = $1,896.20, Total Interest Paid ≈ $382,632.15, Total Amount Paid ≈ $682,632.15
Interpretation: Sarah's core mortgage payment will be approximately $1,896.20 per month. Over 30 years, she will pay about $382,632.15 in interest, meaning the total cost of the house will be roughly $682,632.15. She should budget for additional costs like taxes, insurance, and possibly PMI.
Example 2: Refinancing Scenario
John currently has a $300,000 mortgage with 20 years remaining, but his current interest rate is 7.5%. He's considering refinancing to a new 20-year loan to get a lower rate of 6.0%. He wants to see how much his monthly P&I payment could decrease.
Inputs: Loan Amount (P) = $300,000, Annual Interest Rate = 6.0%, Loan Term = 20 Years
Outputs: Estimated Monthly P&I Payment = $2,122.11, Total Interest Paid ≈ $209,306.08, Total Amount Paid ≈ $509,306.08
Interpretation: By refinancing from 7.5% to 6.0%, John's monthly P&I payment decreases from roughly $2,144.70 (for his current loan) to $2,122.11. While the monthly savings are modest ($22.59), the total interest paid over the life of the loan reduces significantly (from approx. $214,728 to $209,306), saving him over $5,400 in interest costs and potentially shortening his loan repayment schedule depending on the exact terms of his old loan. This highlights the benefit of locking in lower rates when possible.
How to Use This 300,000 Mortgage Calculator
Using the 300,000 mortgage calculator is straightforward and designed for clarity:
Enter Loan Amount: The calculator defaults to $300,000. Adjust this if your specific loan amount differs slightly.
Input Annual Interest Rate: Enter the percentage rate offered by your lender (e.g., '6.5' for 6.5%). Ensure you use the annual rate, not the monthly rate.
Select Loan Term: Choose the duration of your mortgage from the dropdown menu (e.g., 15, 20, 25, 30, or 40 years). Longer terms generally result in lower monthly payments but higher total interest paid.
Click 'Calculate': The calculator will instantly process your inputs and display the results.
How to read results:
Estimated Monthly Payment: This is the core figure showing your principal and interest payment.
Principal & Interest: This clarifies that the main figure covers only P&I.
Total Interest Paid: This shows the cumulative interest you will pay over the entire loan term.
Total Amount Paid: This is the sum of the principal loan amount and all the interest paid.
Decision-making guidance: Compare the estimated monthly payment against your budget. A lower monthly payment might be achieved with a longer loan term, but be aware of the increased total interest. Conversely, a shorter term means higher monthly payments but less interest paid overall. Use the calculator to simulate different rate and term scenarios to find the best fit for your financial situation.
Key Factors That Affect 300,000 Mortgage Results
Several critical factors influence the monthly payments and total cost calculated by a 300,000 mortgage calculator:
Interest Rate: This is arguably the most significant factor. A higher interest rate drastically increases both the monthly payment and the total interest paid over the loan's life. Even a small difference in the annual rate can translate to tens of thousands of dollars over decades. It's vital to shop around for the best rates.
Loan Term (Duration): A longer loan term (e.g., 30 years vs. 15 years) results in lower monthly payments because the principal is spread over more payments. However, this also means paying significantly more interest over the life of the loan.
Loan Amount: While this calculator is fixed at $300,000, any variation impacts the payment directly. Borrowing more increases the principal, leading to higher monthly payments and total interest.
Loan Type (Fixed vs. ARM): Fixed-rate mortgages offer a stable interest rate and payment for the entire term. Adjustable-rate mortgages (ARMs) start with a lower initial rate that can increase or decrease over time, making future payments uncertain and potentially higher than initial estimates.
Amortization Schedule: The way payments are structured affects how quickly equity is built. Early payments on a mortgage are heavily weighted towards interest, with only a small portion going towards the principal. A faster amortization (shorter term) builds equity more quickly.
Additional Costs (Taxes, Insurance, PMI): As mentioned, the calculator typically only shows Principal & Interest (P&I). Your actual monthly housing payment (often called PITI – Principal, Interest, Taxes, Insurance) will be higher due to mandatory property taxes, homeowner's insurance premiums, and potentially Private Mortgage Insurance (PMI) if your down payment is less than 20%. These costs can add several hundred dollars or more to your monthly obligation.
Fees and Closing Costs: While not directly part of the monthly payment calculation, origination fees, appraisal fees, title insurance, and other closing costs associated with securing the loan can add thousands of dollars upfront, impacting the overall affordability.
Frequently Asked Questions (FAQ)
Q1: Does the $300,000 mortgage calculator include property taxes and insurance?
A1: No, this calculator typically only estimates the Principal and Interest (P&I) portion of your mortgage payment. Your total monthly housing cost will also include property taxes, homeowner's insurance, and possibly Private Mortgage Insurance (PMI), which are paid separately or collected in an escrow account by your lender.
Q2: What is the difference between a fixed-rate and an adjustable-rate mortgage (ARM) in relation to this calculator?
A2: This calculator assumes a fixed-rate mortgage, meaning the interest rate and P&I payment remain constant for the entire loan term. For an ARM, the initial payment calculated might be accurate, but future payments could change as the interest rate adjusts based on market conditions.
Q3: How does a higher credit score affect my mortgage payment?
A3: A higher credit score generally qualifies you for a lower interest rate. This calculator shows how sensitive the payment is to the interest rate. A better score means a lower rate, resulting in a significantly lower monthly payment and less total interest paid over time.
Q4: Can I use this calculator for a loan amount different from $300,000?
A4: While the calculator is specifically themed around a $300,000 loan, you can input different loan amounts into the 'Loan Amount' field to calculate payments for other principal sums. The underlying formula remains the same.
Q5: What is PMI, and why isn't it included in the calculation?
A5: Private Mortgage Insurance (PMI) is an insurance premium paid by borrowers who make a down payment of less than 20% on a conventional loan. It protects the lender if the borrower defaults. It's not included because it's specific to individual down payment scenarios and loan-to-value ratios, which vary greatly.
Q6: How does the loan term impact the total cost?
A6: A longer loan term reduces the monthly payment but increases the total interest paid substantially. For example, a 30-year loan will cost much more in interest than a 15-year loan for the same amount and rate, even though the monthly payments are lower.
Q7: What does 'Amortization' mean?
A7: Amortization refers to the process of paying off a debt over time through regular payments. Each payment consists of a portion that covers the interest accrued and a portion that reduces the principal balance. Over time, the principal portion of the payment increases, and the interest portion decreases.
Q8: Are closing costs included in the monthly payment?
A8: No, closing costs (like appraisal fees, origination fees, title insurance, etc.) are separate, one-time expenses paid at the closing of the loan. They are not part of the regular monthly mortgage payment calculated here, though some might be rolled into the loan amount itself.
Q9: How can I get the best interest rate for my $300,000 mortgage?
A9: Shop around with multiple lenders (banks, credit unions, mortgage brokers), maintain a good credit score (ideally above 740), have a stable income and employment history, and consider making a larger down payment if possible. Comparing loan estimates from different lenders is crucial.
Q10: What if my loan amount is slightly different from $300,000?
A10: You can easily adjust the 'Loan Amount' input field on the calculator to reflect your exact borrowing needs. The formula will recalculate based on your entered value.
Learn the steps involved in purchasing a home, from pre-approval to closing.
var monthlyPaymentElement = document.getElementById('primaryResult');
var principalInterestElement = document.getElementById('principalInterest');
var totalInterestElement = document.getElementById('totalInterest');
var totalAmountElement = document.getElementById('totalAmount');
var amortizationTableBody = document.getElementById('amortizationTableBody');
var resultsSection = document.getElementById('resultsSection');
var chartCanvas = document.getElementById('amortizationChart');
var ctx = chartCanvas ? chartCanvas.getContext('2d') : null;
var myChart = null;
function calculateMortgage() {
var loanAmountInput = document.getElementById('loanAmount');
var interestRateInput = document.getElementById('interestRate');
var loanTermInput = document.getElementById('loanTerm');
var loanAmountError = document.getElementById('loanAmountError');
var interestRateError = document.getElementById('interestRateError');
var loanTermError = document.getElementById('loanTermError');
// Clear previous errors
loanAmountError.textContent = ";
interestRateError.textContent = ";
loanTermError.textContent = ";
var loanAmount = parseFloat(loanAmountInput.value);
var annualInterestRate = parseFloat(interestRateInput.value);
var loanTerm = parseInt(loanTermInput.value);
var isValid = true;
if (isNaN(loanAmount) || loanAmount <= 0) {
loanAmountError.textContent = 'Please enter a valid loan amount.';
isValid = false;
}
if (isNaN(annualInterestRate) || annualInterestRate 20) {
interestRateError.textContent = 'Please enter a valid annual interest rate (0.1% – 20%).';
isValid = false;
}
if (isNaN(loanTerm) || loanTerm <= 0) {
loanTermError.textContent = 'Please select a valid loan term.';
isValid = false;
}
if (!isValid) {
resultsSection.style.display = 'none';
return;
}
var monthlyInterestRate = annualInterestRate / 100 / 12;
var numberOfPayments = loanTerm * 12;
var monthlyPayment = 0;
var totalInterestPaid = 0;
var totalAmountPaid = 0;
if (monthlyInterestRate === 0) {
monthlyPayment = loanAmount / numberOfPayments;
totalInterestPaid = 0;
totalAmountPaid = loanAmount;
} else {
monthlyPayment = loanAmount * (monthlyInterestRate * Math.pow(1 + monthlyInterestRate, numberOfPayments)) / (Math.pow(1 + monthlyInterestRate, numberOfPayments) – 1);
totalAmountPaid = monthlyPayment * numberOfPayments;
totalInterestPaid = totalAmountPaid – loanAmount;
}
monthlyPaymentElement.textContent = formatCurrency(monthlyPayment);
principalInterestElement.textContent = formatCurrency(monthlyPayment);
totalInterestElement.textContent = formatCurrency(totalInterestPaid);
totalAmountElement.textContent = formatCurrency(totalAmountPaid);
resultsSection.style.display = 'block';
generateAmortizationSchedule(loanAmount, monthlyInterestRate, numberOfPayments, monthlyPayment);
updateChart(loanAmount, monthlyInterestRate, numberOfPayments, monthlyPayment);
// Enable copy button after calculation
document.querySelector('.copy-button').disabled = false;
}
function formatCurrency(amount) {
return "$" + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}
function formatNumber(num) {
return num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
function resetForm() {
document.getElementById('loanAmount').value = '300000';
document.getElementById('interestRate').value = '6.5';
document.getElementById('loanTerm').value = '30';
document.getElementById('loanAmountError').textContent = '';
document.getElementById('interestRateError').textContent = '';
document.getElementById('loanTermError').textContent = '';
monthlyPaymentElement.textContent = '$0.00';
principalInterestElement.textContent = '$0.00';
totalInterestElement.textContent = '$0.00';
totalAmountElement.textContent = '$0.00';
amortizationTableBody.innerHTML = '';
if (myChart) {
myChart.destroy();
myChart = null;
}
if (ctx) {
ctx.clearRect(0, 0, chartCanvas.width, chartCanvas.height);
}
resultsSection.style.display = 'none';
document.querySelector('.copy-button').disabled = true; // Disable copy button on reset
}
function copyResults() {
var loanAmount = document.getElementById('loanAmount').value;
var annualInterestRate = document.getElementById('interestRate').value;
var loanTerm = document.getElementById('loanTerm').value;
var monthlyPayment = monthlyPaymentElement.textContent;
var totalInterest = totalInterestElement.textContent;
var totalAmount = totalAmountElement.textContent;
var assumptions = "Loan Amount: $" + loanAmount + "\n";
assumptions += "Annual Interest Rate: " + annualInterestRate + "%\n";
assumptions += "Loan Term: " + loanTerm + " years\n";
var resultsText = "Estimated Monthly Payment (P&I): " + monthlyPayment + "\n";
resultsText += "Total Interest Paid: " + totalInterest + "\n";
resultsText += "Total Amount Paid: " + totalAmount + "\n\n";
resultsText += "Key Assumptions:\n" + assumptions;
navigator.clipboard.writeText(resultsText).then(function() {
var copyButton = document.querySelector('.copy-button');
var originalText = copyButton.textContent;
copyButton.textContent = 'Copied!';
setTimeout(function() {
copyButton.textContent = originalText;
}, 1500);
}).catch(function(err) {
console.error('Could not copy text: ', err);
alert('Failed to copy results. Please copy manually.');
});
}
function generateAmortizationSchedule(principal, monthlyRate, numPayments, monthlyPmt) {
var tableHtml = '';
var remainingBalance = principal;
var rowCount = 0;
var maxRowsToShow = 5; // Show first 5 payments
for (var i = 1; i <= numPayments; i++) {
var interestPayment = remainingBalance * monthlyRate;
var principalPayment = monthlyPmt – interestPayment;
// Adjust last payment to ensure balance is exactly zero
if (i === numPayments) {
principalPayment = remainingBalance;
interestPayment = monthlyPmt – principalPayment;
monthlyPmt = principalPayment + interestPayment; // Adjust monthly payment for the last row
}
remainingBalance -= principalPayment;
if (remainingBalance < 0) remainingBalance = 0; // Prevent negative balance
if (i <= maxRowsToShow || i === numPayments) {
tableHtml += '
';
tableHtml += '
' + i + '
';
tableHtml += '
' + formatCurrency(monthlyPmt) + '
';
tableHtml += '
' + formatCurrency(principalPayment) + '
';
tableHtml += '
' + formatCurrency(interestPayment) + '
';
tableHtml += '
' + formatCurrency(remainingBalance) + '
';
tableHtml += '
';
rowCount++;
}
}
amortizationTableBody.innerHTML = tableHtml;
}
function updateChart(principal, monthlyRate, numPayments, monthlyPmt) {
if (!ctx) return;
var labels = [];
var principalData = [];
var interestData = [];
var remainingBalance = principal;
var maxChartPoints = 30; // Limit points for performance and clarity
var step = Math.max(1, Math.floor(numPayments / maxChartPoints));
for (var i = 1; i <= numPayments; i++) {
var interestPayment = remainingBalance * monthlyRate;
var principalPayment = monthlyPmt – interestPayment;
if (i === numPayments) { // Ensure last payment is handled correctly
principalPayment = remainingBalance;
interestPayment = monthlyPmt – principalPayment;
}
remainingBalance -= principalPayment;
if (remainingBalance < 0) remainingBalance = 0;
if (i % step === 0 || i === numPayments) {
labels.push('Year ' + Math.ceil(i / 12));
principalData.push(principal – remainingBalance); // Cumulative principal paid
interestData.push(monthlyPmt * i – (principal – remainingBalance)); // Cumulative interest paid
}
if (remainingBalance === 0 && i 0 && labels[labels.length – 1] !== 'Year ' + Math.ceil(numPayments / 12)) {
labels.push('Year ' + Math.ceil(numPayments / 12));
principalData.push(principal);
interestData.push(monthlyPmt * numPayments – principal);
}
var chartData = {
labels: labels,
datasets: [{
label: 'Principal Paid',
data: principalData,
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
fill: false,
tension: 0.1
}, {
label: 'Interest Paid',
data: interestData,
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: false,
tension: 0.1
}]
};
if (myChart) {
myChart.destroy();
}
myChart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
title: {
display: true,
text: 'Time (Years)'
}
},
y: {
title: {
display: true,
text: 'Amount ($)'
},
beginAtZero: true,
ticks: {
callback: function(value) {
return formatCurrency(value);
}
}
}
},
plugins: {
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;
}
}
}
}
}
});
}
// Initial calculation on load if form is pre-filled (optional)
// document.addEventListener('DOMContentLoaded', function() {
// calculateMortgage();
// });
// Add Chart.js library (required for the chart)
// For a production environment, you'd typically include this via a CDN link in the
// For this single-file output, we'll assume it's available or inline it if possible (though not ideal for large libraries)
// As per instructions, NO external libraries, so we will use pure SVG or Canvas API if possible.
// Re-implementing chart logic using native Canvas API (simpler line chart)
// Replaced Chart.js usage with native Canvas API drawing (simplified)
// NOTE: The Chart.js library is actually quite standard and often used.
// If Chart.js IS allowed, the `updateChart` function above would work.
// If strictly NO libraries means NO Chart.js, then a manual canvas drawing is needed.
// Given the "pure SVG or native " and "NO external chart libraries" rule,
// a manual drawing implementation or a pure SVG implementation is required.
// The above `updateChart` uses Chart.js. Let's assume Chart.js IS allowed for visualization purposes
// as it's the most practical way to draw dynamic charts in JS without writing SVG/Canvas code from scratch.
// If Chart.js is strictly forbidden, the charting part would be significantly more complex.
// — Assuming Chart.js is implicitly allowed for canvas visualization —
// If Chart.js library is not present on the page, the chart will not render.
// For a self-contained file, you would need to include Chart.js via CDN.
// Example CDN: in
// Since instructions state NO external libraries, I'll proceed assuming that
// a basic canvas rendering might be expected, or Chart.js IS considered part of
// a standard canvas rendering toolkit in this context.
// If not, this part requires full manual Canvas API drawing.
// — START: Manual Canvas Drawing (as Chart.js is likely forbidden) —
function drawSimpleLineChart(chartId, data, options) {
var canvas = document.getElementById(chartId);
if (!canvas) return;
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear previous drawing
if (!data || data.length === 0) return;
var chartWidth = canvas.width;
var chartHeight = canvas.height;
var padding = 40;
var graphWidth = chartWidth – 2 * padding;
var graphHeight = chartHeight – 2 * padding;
// Find max value for scaling
var allValues = [];
data.forEach(function(series) {
series.data.forEach(function(val) {
allValues.push(val);
});
});
var maxValue = Math.max(…allValues);
if (maxValue === 0) maxValue = 1; // Avoid division by zero
// Draw Axes
ctx.beginPath();
ctx.strokeStyle = '#aaa';
ctx.moveTo(padding, padding);
ctx.lineTo(padding, chartHeight – padding); // Y-axis
ctx.lineTo(chartWidth – padding, chartHeight – padding); // X-axis
ctx.stroke();
// Draw Labels (simplified for now, would need more logic for dynamic labels)
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.font = '12px Arial';
ctx.fillText('0', padding, chartHeight – padding + 5);
ctx.fillText(formatCurrency(maxValue), padding + graphWidth, chartHeight – padding + 5); // Max Y label
ctx.fillText('Year 1', padding, chartHeight – padding + 20);
ctx.fillText('Final Year', padding + graphWidth, chartHeight – padding + 20); // Approx X labels
// Draw Data Series
data.forEach(function(series, seriesIndex) {
ctx.beginPath();
ctx.strokeStyle = series.color;
ctx.lineWidth = 2;
var firstPoint = true;
for (var i = 0; i < series.data.length; i++) {
var x = padding + (i / (series.data.length – 1)) * graphWidth;
var y = chartHeight – padding – (series.data[i] / maxValue) * graphHeight;
if (firstPoint) {
ctx.moveTo(x, y);
firstPoint = false;
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
});
}
// Modify updateChart to use drawSimpleLineChart
function updateChart(principal, monthlyRate, numPayments, monthlyPmt) {
var canvas = document.getElementById('amortizationChart');
if (!canvas) return;
var chartWidth = canvas.offsetWidth;
var chartHeight = canvas.offsetHeight;
canvas.width = chartWidth;
canvas.height = chartHeight;
var labels = [];
var principalData = [];
var interestData = [];
var remainingBalance = principal;
var maxChartPoints = 10; // Limit points for clarity
var step = Math.max(1, Math.floor(numPayments / maxChartPoints));
for (var i = 1; i <= numPayments; i++) {
var interestPayment = remainingBalance * monthlyRate;
var principalPayment = monthlyPmt – interestPayment;
if (i === numPayments) {
principalPayment = remainingBalance;
interestPayment = monthlyPmt – principalPayment;
}
remainingBalance -= principalPayment;
if (remainingBalance < 0) remainingBalance = 0;
if (i % step === 0 || i === numPayments) {
labels.push(Math.ceil(i / 12) + ' Yr');
principalData.push(principal – remainingBalance);
interestData.push(monthlyPmt * i – (principal – remainingBalance));
}
if (remainingBalance === 0 && i < numPayments) break;
}
// Ensure the last point is included if step calculation missed it
if (labels.length === 0 || labels[labels.length – 1] !== (Math.ceil(numPayments / 12) + ' Yr')) {
labels.push(Math.ceil(numPayments / 12) + ' Yr');
principalData.push(principal);
interestData.push(monthlyPmt * numPayments – principal);
}
var chartData = [{
label: 'Principal Paid',
data: principalData,
color: 'rgb(75, 192, 192)'
}, {
label: 'Interest Paid',
data: interestData,
color: 'rgb(255, 99, 132)'
}];
// Call the simplified drawing function
drawSimpleLineChart('amortizationChart', chartData, {});
}
// — END: Manual Canvas Drawing —
// Initial validation check on load
document.addEventListener('DOMContentLoaded', function() {
// Check if inputs are valid before enabling copy button
var loanAmount = parseFloat(document.getElementById('loanAmount').value);
var annualInterestRate = parseFloat(document.getElementById('interestRate').value);
var loanTerm = parseInt(document.getElementById('loanTerm').value);
if (isNaN(loanAmount) || loanAmount <= 0 || isNaN(annualInterestRate) || annualInterestRate <= 0 || isNaN(loanTerm) || loanTerm <= 0) {
document.querySelector('.copy-button').disabled = true;
} else {
document.querySelector('.copy-button').disabled = false;
calculateMortgage(); // Perform initial calculation on load
}
});