The Code For Mortgage Calculator
//Retrieving the values from the page
function getValues(){
//making the empty table invisible
document.getElementById("table").classList.add("invisible");
let mortgageAmount = document.getElementById("mortgageAmountInput").value;
let months = document.getElementById("totalMonthsInput").value;
let rate = document.getElementById("rateInput").value;
if (mortgageAmount == ""){
mortgageAmount = parseFloat(380000);
} else {
mortgageAmount = parseFloat(mortgageAmount);
}
if (months == ""){
months = parseFloat(300);
} else {
months = parseFloat(months);
}
if (rate == "") {
rate = parseFloat(4);
} else {
rate = parseFloat(rate);
}
//Mortgage calculation
let resultsHTML = mortgageCalculation(mortgageAmount, rate, months);
//show the html to the user
displayResults(resultsHTML);
}
// Calculations for the amorization schedule
function mortgageCalculation(mortgageAmount, rate, months){
let resultsObject = {};
let totalInterest = 0;
let balance = mortgageAmount;
let interestPayment = 0;
let principalPayment;
// Caclulation of the total monthly payment
let monthExponent = -Math.abs(months);
let monthlyPayment = (mortgageAmount * (rate/1200)) / (1-(1+(rate/1200))**(monthExponent));
monthlyPayment = parseFloat(monthlyPayment);
let html = "";
for (let i = 1; i <= months; i++){
let month = i;
interestPayment = parseFloat(balance*(rate/1200));
principalPayment = parseFloat(monthlyPayment - (balance * (rate/1200)));
totalInterest = parseFloat((totalInterest + interestPayment));
totalInterest = parseFloat(totalInterest);
balance -= principalPayment;
balance = Math.abs(parseFloat(balance));
html += `<tr><td>${month}</td><td>${monthlyPayment.toFixed(2)}</td><td>${principalPayment.toFixed(2)}</td><td>${interestPayment.toFixed(2)}</td><td>${totalInterest.toFixed(2)}</td><td>${balance.toFixed(2)}</td></tr>`
}
let totalCost = mortgageAmount + totalInterest;
//Using the .toLocaleString to convert to $ format
//Displaying the calculated data in the correct places accordingly
resultsObject.monthlyPayment = monthlyPayment.toLocaleString('en-US',{style: 'currency', currency:'USD'});
resultsObject.totalPrincipal = mortgageAmount.toLocaleString('en-US',{style: 'currency', currency:'USD'});
resultsObject.totalInterest = totalInterest.toLocaleString('en-US',{style: 'currency', currency:'USD'});
resultsObject.totalCost = totalCost.toLocaleString('en-US',{style: 'currency', currency:'USD'});
resultsObject.html = html;
return resultsObject;
}
// Displaying the results
function displayResults(resultsObject){
document.getElementById("monthPaymentsOutput").innerHTML = resultsObject.monthlyPayment;
document.getElementById("totalPrincipalOutput").innerHTML = resultsObject.totalPrincipal;
document.getElementById("totalInterestOutput").innerHTML = resultsObject.totalInterest;
document.getElementById("totalCostOutput").innerHTML = resultsObject.totalCost;
document.getElementById("results").innerHTML = resultsObject.html;
//This will remove the invisible class and allow for visibility accordingly
document.getElementById("table").classList.remove("invisible");
}
// Making the reset button functional
function resetPage(){
//Making the empty table invisible
document.getElementById("table").classList.add("invisible");
mortgageAmount = document.getElementById("mortgageAmountInput").value = "";
months = document.getElementById("totalMonthsInput").value = "";
rate = document.getElementById("rateInput").value = "";
document.getElementById("monthPaymentsOutput").innerHTML ="";
document.getElementById("totalPrincipalOutput").innerHTML ="";
document.getElementById("totalInterestOutput").innerHTML ="";
document.getElementById("totalCostOutput").innerHTML ="";
document.getElementById("results").innerHTML = "";
}
Description
The code can be broken down into four main functions:
1.) getValues()
The JavaScript code of this application begins with the getValues function. The very first step is to ensure that the empty table is not visible. Making the empty table invisible is done by adding the invisible class. The getValues function starts when the calculate button is clicked. If the user decides not to enter any values, the user may proceed with the provided placeholder values to demo the application. This function takes the user input or the placeholders and passes them on to the mortgageCalculation function. Lastly, the HTML string is passed on to the displayResults function to make the data visible to the user accordingly.
2.) mortgageCalculation()
In this function, all of the calculations will be executed and, I have also utilized resultsObject to hold all of data that will be returned. After I created the necessary variables for generating the output and table rows, I set up the monthly payment calculation using parseFloat to ensure that the input is not a string. Depending on the selected mortgage term, the loop will increment as many times as specified, starting at the index of 1. For each month the values differ due to our formulas, the balance and total interest are updated before they are inserted and become a row in an HTML table. Rounded monthly payment values will be displayed to the user with the help of the .toFixed(2) method. I am not using rounded values in the calculations, and the variable monthlyPayment does not contain rounded values. If rounded values were used for the calculations, errors would occur along the way. To prevent the balance from displaying a negative value when it gets to $0, I have used the Math.abs function to display the absolute values.
The final step in the calculation process is to calculate the total by utilizing the user input. There is a designated section in the code that holds variables that were calculated in resultsObject. Before the resultsObject is returned, I have also converted the monetary values to USD currency format.
3.) displayResults()
In this section of the code, I have implemented the functionality that allows us to render and display the results to the user. The invisible class is removed to display the result. The main functionality here is that the values from resultsObject are placed into the correct element, the data will be displayed in columns and rows. I have used the same function in another coding challenge named FizzBuzz in which the same function is called displayData. To find a more detailed explanation of this function, click here. Search for section three on the code explanation page with the heading "The View Function".
4.) resetPage()
The reset page function allows the user to clear their input, and it gives them a chance to start over without refreshing the page. The page is reset by setting the inner HTML of the elements to empty strings. I also added the invisible class again to ensure that the empty table is not visible. Once the user presses the calculate button, the invisible class will be removed again.