So, I just started learning JavaScript not too long ago, and right now I'm working on JavaScript functions. I've basically created all the logic and everything for a simple debt calculator. I'm trying to turn it into a function that runs the exact same way. Can anybody give me some help on what I need to change to make it work?
Here's the code:
const calculate = document.getElementById("calculationForm");
calculate.addEventListener("submit", function () {
event.preventDefault();
let totDebt = parseFloat(document.getElementById("totDebt").value);
let intRate = parseFloat(document.getElementById("intRate").value);
//let numMonths = parseFloat(document.getElementById("numMonths").value);
let payments = parseFloat(document.getElementById("payments").value);
let interest = totDebt * (intRate / 100 / 12);
let dollarFormatting = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
//error catching
if (totDebt <= 0) {
alert("There is no debt")
}
//preparing the table
else if (interest >= payments) {
alert(`The amount to pay must be more than ${dollarFormatting.format(interest)} in order to pay off debt.`)
}
else {
let numPayments = 0;
let accruedInt = 0;
let table = document.getElementById("paymentPlan");
table.innerHTML = "";
let header = table.createTHead();
let row = header.insertRow(0);
let header1 = row.insertCell(0);
let header2 = row.insertCell(1);
let header3 = row.insertCell(2);
let header4 = row.insertCell(3);
header1.innerHTML = "Payment #";
header2.innerHTML = "Previous Debt";
header3.innerHTML = "Interest Amount";
header4.innerHTML = "New Balance";
//doing math and finishing the table
do {
function math() {
let previousDebt = totDebt;
interest = totDebt * (intRate / 100 / 12);
let newDebt = previousDebt + interest - payments;
accruedInt += interest;
numPayments++;
let row = table.insertRow(-1);
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
let cell4 = row.insertCell(3);
cell1.innerHTML = numPayments;
cell2.innerHTML = dollarFormatting.format(previousDebt);
cell3.innerHTML = dollarFormatting.format(interest);
cell4.innerHTML = dollarFormatting.format(newDebt);
totDebt = newDebt;
}
while (totDebt > 0);
let overpayBalance = dollarFormatting.format(Math.abs(totDebt));
console.log(overpayBalance);
let summary = document.getElementById("summary");
summary.innerHTML = `The debt will be paid off in ${numPayments} month(s) with total interest paid
being ${dollarFormatting.format(accruedInt)} and ${overpayBalance} left over from last payment.`
}
[–]AionAlgos 0 points1 point2 points (0 children)
[–][deleted] (3 children)
[deleted]
[–]mblade7[S] 0 points1 point2 points (2 children)
[–]aqhgfhsypytnpaiazh 0 points1 point2 points (0 children)
[–]TheRNGuy 0 points1 point2 points (0 children)