Percentage of your salary you contribute. (Max 50%)
Employer's matching contribution percentage (e.g., 50% match up to 6% of salary). Enter the effective match percentage.
Anticipated annual increase in your salary.
Average yearly growth rate of your investments.
Number of years you plan to contribute and invest.
Your Retirement Projection
—
Total Contributions: —
Employer Contributions: —
Estimated Investment Growth: —
Key Assumptions:
Assumed Initial Salary: —
Assumed Contribution Rate: —
Assumed Employer Match: —
Assumed Annual Return: —
Assumed Annual Raise: —
Years to Retirement: —
Formula: This calculator estimates your future 401k value by projecting annual contributions (your salary * contribution rate + employer match) and compounding investment growth over your specified years until retirement. Salary is assumed to increase annually.
Annual Contribution Breakdown
Year
Starting Salary
Your Contribution
Employer Match
Total Annual Contribution
Estimated Year-End Balance
Retirement Savings Growth Over Time
What is a 401k Contribution Calculator?
A 401k Contribution Calculator is a powerful online tool designed to help individuals estimate the potential growth of their retirement savings within a 401k plan. It takes into account various factors such as your current salary, the percentage you contribute, your employer's matching contributions, and the expected rate of return on your investments. By inputting these key figures, the calculator provides projections for your total accumulated savings by your planned retirement date. This tool is invaluable for financial planning, allowing you to visualize the impact of different contribution levels and investment strategies on your long-term financial security. Understanding these projections can empower you to make informed decisions about how much to save to meet your retirement goals.
Who Should Use a 401k Contribution Calculator?
Virtually anyone with access to a 401k plan should consider using this calculator, including:
Young Professionals: To understand the long-term benefits of starting early and the power of compounding. Even small, consistent contributions now can grow significantly over decades.
Mid-Career Individuals: To assess if they are on track for retirement, determine if they need to increase their contribution rate, and understand the potential impact of employer matches.
Pre-Retirees: To get a clearer picture of their projected retirement nest egg and make final adjustments to their savings strategy.
Employees Receiving Employer Match: To ensure they are contributing enough to maximize their employer's match, essentially getting "free money" for retirement.
Individuals Considering a Rollover: While this calculator focuses on active contributions, understanding current savings potential is crucial before making any 401k rollover decisions.
Common Misconceptions About 401k Contributions:
"I can't afford to contribute much right now." While understandable, delaying contributions means missing out on crucial years of compounding growth. This calculator can show the long-term cost of deferring savings.
"My employer match is small, so it's not worth it." Even a small match adds up significantly over time, especially when combined with your contributions and investment returns. It's crucial to always aim to get the full employer match.
"My investments will always grow at a fixed rate." Investment returns are not guaranteed and fluctuate. The calculator uses an *expected* average, but actual results may vary. Diversification and realistic return expectations are key.
"I'll just save more later." Time is the most powerful asset in retirement savings. The earlier you start, the less you need to contribute later to reach the same goal due to compounding.
401k Contribution Calculator Formula and Mathematical Explanation
The 401k Contribution Calculator uses a projection model that simulates the growth of your retirement savings year by year. The core logic involves calculating annual contributions and then applying compound interest. Here's a breakdown:
Core Calculation Steps:
Calculate Initial Annual Contributions: Your contribution is your `Current Salary * Contribution Rate`. Your employer's match is typically calculated based on your contribution and their specific matching formula, often expressed as a percentage of your salary up to a certain limit. For simplicity in many calculators, the employer match is entered directly as an effective percentage of your salary, or calculated based on a simplified match rule.
Project Salary Growth: Each subsequent year, your salary increases by the `Annual Raise %`.
Calculate Subsequent Annual Contributions: Your new salary is used to calculate your contribution and the employer match for that year, adjusted for any changes in contribution limits or plan rules (though this calculator simplifies this).
Apply Compound Interest: The total balance at the end of each year (previous year's balance + total contributions for the current year) grows by the `Expected Annual Return %`.
Repeat Annually: Steps 2-4 are repeated for each `Year Until Retirement`.
Variables Table:
Variable
Meaning
Unit
Typical Range
Current Annual Salary
Your gross income before taxes and deductions.
Currency (e.g., USD)
$30,000 – $250,000+
Your Contribution Rate
The percentage of your salary you elect to contribute to your 401k.
Percentage (%)
0% – 50% (often capped by IRS limits)
Employer Match Rate
The percentage of your salary your employer contributes based on your contributions. Varies by plan.
Percentage (%)
0% – 6% (common structures like 50% match on first 6% or dollar-for-dollar up to a limit)
Annual Raise
The expected annual percentage increase in your salary.
Percentage (%)
1% – 5%
Expected Annual Return
The anticipated average annual rate of growth for your investment portfolio.
Percentage (%)
5% – 10% (historical averages, not guaranteed)
Years Until Retirement
The number of years remaining until you plan to stop working and start drawing from your savings.
Years
1 – 45
Mathematical Formula (Simplified Annual Projection):
EndBalanceYear N = (EndBalanceYear N-1 + (SalaryYear N * YourContributionRateYear N) + (SalaryYear N * EmployerMatchRateYear N)) * (1 + ExpectedAnnualReturn)
Where SalaryYear N = SalaryYear N-1 * (1 + AnnualRaise), and initial values are set for Year 0.
This iterative process allows for a dynamic projection, considering salary increases and compounding growth over the entire investment horizon.
Practical Examples (Real-World Use Cases)
Example 1: Young Professional Starting Out
Scenario: Sarah is 25 years old, earns $60,000 annually, and contributes 8% to her 401k. Her employer matches 50% of her contributions up to 6% of her salary. She expects a 3% annual raise and an average annual return of 7%. She plans to retire in 40 years.
Inputs:
Annual Salary: $60,000
Your Contribution Rate: 8%
Employer Match Rate: 3% (50% of 6%)
Expected Annual Raise: 3%
Expected Annual Return: 7%
Years Until Retirement: 40
Calculator Output (Simplified):
Primary Result (Estimated Future Value): ~$1,150,000
Total Contributions (Your + Employer): ~$430,000
Estimated Investment Growth: ~$720,000
Interpretation: By starting early and consistently contributing, even with a moderate salary and employer match, Sarah can build a substantial retirement nest egg exceeding $1 million. This highlights the power of compounding over a long investment horizon.
Example 2: Mid-Career Saver Maximizing Match
Scenario: John is 40 years old, earns $100,000 annually, and currently contributes 10% to his 401k. His employer matches dollar-for-dollar up to 5% of his salary. He expects a 4% annual raise and an average annual return of 8%. He plans to retire in 25 years.
Inputs:
Annual Salary: $100,000
Your Contribution Rate: 10%
Employer Match Rate: 5% (dollar-for-dollar up to 5%)
Expected Annual Raise: 4%
Expected Annual Return: 8%
Years Until Retirement: 25
Calculator Output (Simplified):
Primary Result (Estimated Future Value): ~$820,000
Total Contributions (Your + Employer): ~$430,000
Estimated Investment Growth: ~$390,000
Interpretation: John is contributing more than the match limit. If he increased his contribution to capture the full employer match (5%) and then considered potentially increasing it further, he could significantly boost his future value. For instance, contributing 15% could yield an even higher result. This calculator helps him see the immediate benefit of contributing at least enough to get the full match.
How to Use This 401k Contribution Calculator
Using our 401k Contribution Calculator is straightforward and designed to provide actionable insights into your retirement planning. Follow these simple steps:
Enter Your Annual Salary: Input your current gross annual income before any deductions.
Specify Your Contribution Rate: Enter the percentage of your salary you are currently contributing or wish to contribute to your 401k. Use the slider or the input field.
Input Employer Match Rate: Enter the percentage of your salary your employer contributes as a match. If your employer matches 50% on the first 6% you contribute, the effective match rate you should enter is 3% (0.50 * 6%). Check your plan details for specifics.
Estimate Annual Raise: Provide an expected annual percentage increase for your salary. A conservative estimate (e.g., 2-4%) is often recommended.
Set Expected Annual Return: Input the average annual rate of return you anticipate from your 401k investments. Historical market averages (around 7-10% for diversified portfolios) can be a guide, but remember returns are not guaranteed.
Determine Years to Retirement: Enter the number of years between now and when you plan to retire and start withdrawing from your savings.
Click 'Calculate Contributions': Once all fields are populated, click the button to see your projected retirement savings.
Reading Your Results:
Primary Highlighted Result: This is your estimated total 401k balance at your planned retirement date.
Total Contributions: This sum represents all the money contributed from both you and your employer over the years.
Estimated Investment Growth: This shows the total earnings generated by your investments due to compounding returns. Notice how often this significantly outweighs the total contributions, especially over longer periods.
Key Assumptions: Review these to understand the basis of the calculation and identify areas where you might adjust your inputs (e.g., increasing contribution rate or expecting a different return).
Annual Breakdown Table: Provides a year-by-year view of how your salary, contributions, and balance grow.
Growth Chart: Visually represents the power of compounding, showing the projected increase in your savings over time.
Decision-Making Guidance:
Use the calculator to run 'what-if' scenarios. What if you increased your contribution by 2%? What if you assumed a slightly lower return? Comparing these scenarios can help you set realistic goals and identify concrete actions needed to achieve them. For instance, if your projected balance is lower than desired, the calculator can show how much extra you'd need to save annually or how many more years you might need to work.
Key Factors That Affect 401k Results
Several critical factors influence the outcome of your 401k projections. Understanding these can help you refine your inputs and manage expectations:
Contribution Rate: This is arguably the most significant factor within your control. Higher contribution rates directly increase the principal amount invested, leading to greater potential for compounding growth. Even a small increase can make a substantial difference over decades. This is where focusing on maximizing your 401k contribution limits is vital.
Time Horizon (Years to Retirement): The longer your money is invested, the more time compounding has to work its magic. Starting early is incredibly advantageous. Delaying contributions means you not only miss out on growth but may need to save much more aggressively later to catch up.
Expected Rate of Return: The annual percentage growth of your investments is crucial. Higher returns accelerate wealth accumulation, but they often come with higher risk. Conversely, overly conservative investment choices might not generate enough growth to outpace inflation or meet retirement goals. Choosing an appropriate asset allocation is key.
Employer Match: This is essentially risk-free return on your investment. Always aim to contribute enough to receive the maximum employer match. It significantly boosts your total contributions and accelerates your path to retirement readiness.
Salary Growth: As your salary increases over your career, your ability to contribute more also grows. Higher future salaries often lead to higher future contributions, further fueling the growth of your retirement fund. Realistic salary increase expectations impact long-term projections.
Investment Fees and Expenses: High management fees within your 401k plan can significantly erode returns over time. Even a 1% difference in annual fees can amount to tens or hundreds of thousands of dollars less at retirement. Regularly review fund expense ratios.
Inflation: While not directly inputted into this basic calculator, inflation reduces the purchasing power of your future savings. A projected balance of $1 million in 30 years will buy less than $1 million today. Consider this when setting your retirement income goals.
Taxes: This calculator typically projects pre-tax (Traditional 401k) or post-tax (Roth 401k) growth. Your tax situation in retirement will depend on the type of 401k you have and current tax laws. Withdrawals from Traditional 401ks are taxed as ordinary income in retirement.
Frequently Asked Questions (FAQ)
Q: What is the maximum amount I can contribute to a 401k?
A: For 2024, the IRS limit for employee contributions to a 401k plan is $23,000. Those aged 50 and over can make an additional catch-up contribution of $7,500, bringing their total to $30,500. These limits are subject to change annually.
Q: How is the employer match calculated?
A: Employer matches vary. Common structures include: 50% match on the first 6% of your salary you contribute, or dollar-for-dollar match up to 3-5% of your salary. Always check your specific plan documents. The calculator assumes an *effective* match percentage of your salary.
Q: Should I prioritize a Traditional 401k or a Roth 401k?
A: Traditional 401k contributions are pre-tax, lowering your current taxable income, while withdrawals in retirement are taxed. Roth 401k contributions are made after-tax, offering tax-free withdrawals in retirement. The choice often depends on whether you expect your tax rate to be higher now or in retirement. Consider consulting a financial advisor.
Q: What happens if my actual investment return is different from the expected return?
A: Investment returns fluctuate. If actual returns are consistently higher than your projection, your savings could grow faster. If they are lower, growth will be slower, potentially requiring you to save more or work longer. This calculator provides an estimate based on an average.
Q: Can I withdraw money from my 401k before retirement?
A: Generally, you can withdraw funds from your 401k after age 59½ without penalty. Early withdrawals (before 59½) usually incur a 10% IRS penalty plus ordinary income tax, though exceptions exist for specific hardship situations. It's best to avoid early withdrawals to allow your savings to grow.
Q: Does this calculator account for fees in my 401k?
A: This basic calculator does not explicitly deduct investment fees. High fees can significantly reduce your net returns. It's essential to be aware of the expense ratios of the funds within your 401k plan. Reducing fees is a key part of a successful retirement savings strategy.
Q: What if I change jobs? How does that affect my 401k?
A: When you leave an employer, you typically have several options for your 401k: leave it with the former employer (if allowed), roll it over into your new employer's plan, roll it over into an IRA, or cash it out (not recommended due to taxes and penalties). Understanding your options is crucial for continued long-term investment growth.
Q: How does inflation affect my retirement savings?
A: Inflation erodes the purchasing power of money over time. While your 401k balance might grow nominally, its real value (what it can actually buy) might increase at a slower pace than projected if inflation is high. It's important to factor inflation into your retirement income needs.
Understand the potential costs and penalties associated with taking money from your retirement accounts before age 59½.
// — Global Variables and Initialization —
var currentSalaryInput = document.getElementById("currentSalary");
var contributionRateSlider = document.getElementById("contributionRate");
var contributionRateValueInput = document.getElementById("contributionRateValue");
var employerMatchRateInput = document.getElementById("employerMatchRate");
var annualRaiseInput = document.getElementById("annualRaise");
var expectedAnnualReturnInput = document.getElementById("expectedAnnualReturn");
var yearsToRetirementInput = document.getElementById("yearsToRetirement");
var primaryResultDiv = document.getElementById("primary-result");
var totalContributionsDiv = document.getElementById("totalContributions");
var employerContributionsDiv = document.getElementById("employerContributions");
var totalGrowthDiv = document.getElementById("totalGrowth");
var assumedSalaryDiv = document.getElementById("assumedSalary");
var assumedRateDiv = document.getElementById("assumedRate");
var assumedMatchDiv = document.getElementById("assumedMatch");
var assumedReturnDiv = document.getElementById("assumedReturn");
var assumedRaiseDiv = document.getElementById("assumedRaise");
var assumedYearsDiv = document.getElementById("assumedYears");
var annualContributionsTableBody = document.querySelector("#annualContributionsTable tbody");
var chartCanvas = document.getElementById("savingsGrowthChart");
var chartInstance = null; // To hold the chart object
var defaultValues = {
currentSalary: 75000,
contributionRate: 10,
employerMatchRate: 5,
annualRaise: 3,
expectedAnnualReturn: 7,
yearsToRetirement: 30
};
// — Input Validation Functions —
function validateInput(inputId, minValue, maxValue, errorMessageId, helperTextElement = null) {
var input = document.getElementById(inputId);
var errorDiv = document.getElementById(errorMessageId);
var value = parseFloat(input.value);
errorDiv.style.display = 'none'; // Hide error by default
if (isNaN(value) || input.value.trim() === "") {
errorDiv.textContent = "This field is required.";
errorDiv.style.display = 'block';
return false;
}
if (value maxValue) {
errorDiv.textContent = "Value cannot be greater than " + maxValue + ".";
errorDiv.style.display = 'block';
return false;
}
if (helperTextElement) {
helperTextElement.textContent = helperTextElement.dataset.defaultText; // Restore default text if valid
}
return true;
}
// — Helper Functions —
function formatCurrency(amount) {
return "$" + amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$1,');
}
function formatPercent(percent) {
return percent.toFixed(2) + "%";
}
function updateContributionRateValue(val) {
contributionRateValueInput.value = val;
calculate401k();
}
function updateContributionRateSlider(val) {
contributionRateSlider.value = val;
calculate401k();
}
// — Calculation Logic —
function calculate401k() {
// Clear previous errors
document.querySelectorAll('.error-message').forEach(el => el.style.display = 'none');
// Validate inputs
var isValid = true;
isValid &= validateInput("currentSalary", 0, 1000000, "currentSalaryError");
isValid &= validateInput("contributionRateValue", 0, 50, "contributionRateError"); // Validate based on value input
isValid &= validateInput("employerMatchRate", 0, 20, "employerMatchRateError"); // Increased max for clarity, though typical is lower
isValid &= validateInput("annualRaise", 0, 10, "annualRaiseError");
isValid &= validateInput("expectedAnnualReturn", 0, 15, "expectedAnnualReturnError");
isValid &= validateInput("yearsToRetirement", 1, 50, "yearsToRetirementError");
if (!isValid) {
resetResults(); // Clear results if validation fails
return;
}
var salary = parseFloat(currentSalaryInput.value);
var contributionRate = parseFloat(contributionRateValueInput.value) / 100;
var employerMatchRate = parseFloat(employerMatchRateInput.value) / 100;
var annualRaise = parseFloat(annualRaiseInput.value) / 100;
var expectedAnnualReturn = parseFloat(expectedAnnualReturnInput.value) / 100;
var yearsToRetirement = parseInt(yearsToRetirementInput.value);
var currentSalary = salary;
var totalContributions = 0;
var totalEmployerContributions = 0;
var totalGrowth = 0;
var currentBalance = 0;
var annualData = [];
// Update assumptions display
assumedSalaryDiv.textContent = "Assumed Initial Salary: " + formatCurrency(salary);
assumedRateDiv.textContent = "Assumed Contribution Rate: " + formatPercent(contributionRate * 100);
assumedMatchDiv.textContent = "Assumed Employer Match: " + formatPercent(employerMatchRate * 100);
assumedReturnDiv.textContent = "Assumed Annual Return: " + formatPercent(expectedAnnualReturn * 100);
assumedRaiseDiv.textContent = "Assumed Annual Raise: " + formatPercent(annualRaise * 100);
assumedYearsDiv.textContent = "Years to Retirement: " + yearsToRetirement;
for (var year = 1; year <= yearsToRetirement; year++) {
var yourContribution = currentSalary * contributionRate;
// Simplified employer match calculation: based on the defined rate of the current salary.
// More complex plans might match only up to a certain personal contribution rate.
var employerContribution = currentSalary * employerMatchRate;
var totalAnnualContribution = yourContribution + employerContribution;
// Calculate growth for the year
var growthThisYear = (currentBalance + totalAnnualContribution) * expectedAnnualReturn;
// Update balance
currentBalance += totalAnnualContribution + growthThisYear;
// Accumulate totals
totalContributions += yourContribution;
totalEmployerContributions += employerContribution;
totalGrowth += growthThisYear;
annualData.push({
year: year,
startSalary: currentSalary,
yourContribution: yourContribution,
employerContribution: employerContribution,
totalContribution: totalAnnualContribution,
endBalance: currentBalance
});
// Project salary for the next year
currentSalary = currentSalary * (1 + annualRaise);
}
// — Display Results —
primaryResultDiv.textContent = formatCurrency(currentBalance);
totalContributionsDiv.textContent = "Total Contributions (You + Employer): " + formatCurrency(totalContributions + totalEmployerContributions);
employerContributionsDiv.textContent = "Total Employer Contributions: " + formatCurrency(totalEmployerContributions);
totalGrowthDiv.textContent = "Estimated Investment Growth: " + formatCurrency(totalGrowth);
// — Populate Table —
annualContributionsTableBody.innerHTML = ''; // Clear previous table data
annualData.forEach(function(data) {
var row = annualContributionsTableBody.insertRow();
row.insertCell(0).textContent = data.year;
row.insertCell(1).textContent = formatCurrency(data.startSalary);
row.insertCell(2).textContent = formatCurrency(data.yourContribution);
row.insertCell(3).textContent = formatCurrency(data.employerContribution);
row.insertCell(4).textContent = formatCurrency(data.totalContribution);
row.insertCell(5).textContent = formatCurrency(data.endBalance);
});
// — Update Chart —
updateChart(annualData, yearsToRetirement);
}
// — Charting Logic —
function updateChart(annualData, years) {
if (chartInstance) {
chartInstance.destroy(); // Destroy previous chart instance if it exists
}
var labels = [];
var yourTotalContributions = []; // Cumulative from user
var employerTotalContributions = []; // Cumulative from employer
var totalBalances = [];
var currentUserContribTotal = 0;
var currentEmployerContribTotal = 0;
for (var i = 0; i el.textContent = ");
calculate401k(); // Recalculate with default values
}
function resetResults() {
primaryResultDiv.textContent = "–";
totalContributionsDiv.textContent = "Total Contributions: –";
employerContributionsDiv.textContent = "Employer Contributions: –";
totalGrowthDiv.textContent = "Estimated Investment Growth: –";
annualContributionsTableBody.innerHTML = ";
if (chartInstance) {
chartInstance.destroy();
chartInstance = null;
}
}
// — Copy Results Functionality —
function copyResults() {
var resultsText = "401k Contribution Calculator Results:\n\n";
resultsText += "Estimated Future Value: " + primaryResultDiv.textContent + "\n";
resultsText += totalContributionsDiv.textContent + "\n";
resultsText += employerContributionsDiv.textContent + "\n";
resultsText += totalGrowthDiv.textContent + "\n\n";
resultsText += "Key Assumptions:\n";
resultsText += assumedSalaryDiv.textContent.replace("Assumed Initial Salary: ", "Initial Salary: ") + "\n";
resultsText += assumedRateDiv.textContent.replace("Assumed Contribution Rate: ", "Contribution Rate: ") + "\n";
resultsText += assumedMatchDiv.textContent.replace("Assumed Employer Match: ", "Employer Match: ") + "\n";
resultsText += assumedReturnDiv.textContent.replace("Assumed Annual Return: ", "Annual Return: ") + "\n";
resultsText += assumedRaiseDiv.textContent.replace("Assumed Annual Raise: ", "Annual Raise: ") + "\n";
resultsText += assumedYearsDiv.textContent.replace("Years to Retirement: ", "Years to Retirement: ") + "\n\n";
resultsText += "Annual Breakdown:\n";
var rows = annualContributionsTableBody.querySelectorAll('tr');
if (rows.length > 0) {
var headerCells = document.querySelectorAll("#annualContributionsTable thead th");
var headerText = [];
headerCells.forEach(th => headerText.push(th.textContent));
resultsText += headerText.join('\t') + '\n'; // Use tab for spacing
rows.forEach(function(row) {
var cells = row.querySelectorAll('td');
var rowData = [];
cells.forEach(td => rowData.push(td.textContent));
resultsText += rowData.join('\t') + '\n';
});
} else {
resultsText += "No annual data available.\n";
}
// Use temporary textarea to copy
var textArea = document.createElement("textarea");
textArea.value = resultsText;
textArea.style.position = "fixed"; // Avoid scrolling to bottom
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'Results copied to clipboard!' : 'Failed to copy results.';
// Optionally show a temporary message to the user
console.log(msg);
// Add a temporary success message near the button
var copyButton = document.querySelector('.btn-copy');
var originalText = copyButton.textContent;
copyButton.textContent = 'Copied!';
setTimeout(function() {
copyButton.textContent = originalText;
}, 1500);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
// Add a temporary error message
var copyButton = document.querySelector('.btn-copy');
var originalText = copyButton.textContent;
copyButton.textContent = 'Copy Failed';
setTimeout(function() {
copyButton.textContent = originalText;
}, 1500);
}
document.body.removeChild(textArea);
}
// — Initial Calculation & Chart Load —
document.addEventListener('DOMContentLoaded', function() {
// Load chart library (Chart.js) – Assume it's included externally or available globally
// For this single file requirement, we will embed it here.
var chartJsScript = document.createElement('script');
chartJsScript.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js'; // Use a specific version
chartJsScript.onload = function() {
console.log("Chart.js loaded.");
calculate401k(); // Calculate once Chart.js is loaded
};
chartJsScript.onerror = function() {
console.error("Failed to load Chart.js. Chart will not be available.");
// Update UI or show error message if chart fails to load
var chartContainer = document.querySelector('.chart-container');
if(chartContainer) {
chartContainer.innerHTML = "
Chart could not be loaded. Please check your internet connection.
";
}
};
document.head.appendChild(chartJsScript);
// Add default text to helper texts for copy/paste in validation reset
document.querySelectorAll('.input-group .helper-text').forEach(function(el) {
el.dataset.defaultText = el.textContent;
});
});
// Re-calculate on input change for real-time updates
document.addEventListener('input', function(event) {
if (event.target.closest('.loan-calc-container') || event.target.closest('.results-section')) {
// Debounce or throttle if performance becomes an issue, but for now, direct call
calculate401k();
}
});
// Initial call to set default values on page load
// calculate401k(); // Moved to chartJsScript.onload