js - how to output values from function into HTML table

主宰稳场 提交于 2021-02-20 04:33:30

问题


I've created a calculator to show repayments over the term of the loan.

I've managed to calculate each months payment, interest, remaining loan but I'm trying to output this into a table. The columns will be a fixed number (5) but the rows should dynamically update based on the number of months.

I've seen a few similar posts but can't get it to work for my code.

Code below and in jsfiddle

HTML

<div class="mortgageInput">
  <form method="POST" name="calc" onclick="validateForm();repayment();return false;">
    <label>Amount </label>
    <input type="textbox" id="loan" value="100000"><br>
    <label>Years</label>
    <input type="textbox" id="years" value="15"><br>
    <label>Rate (%)</label>
    <input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
    <input type="button" value="Calculate" id="btn"><br>
    <label>Monthly Repayment</label>
    <input type="textbox" id="monthlyRepayment"><br>
    <label>Monthly Interest Only</label>
    <input type="textbox" id="interest"><br>
    <label>Monthly Capital Repayment</label>
    <input type="textbox" id="capitalRepayment"><br>
    <label>Total Interest</label>
    <input type="textbox" id="totalInterest">
  </form>
</div>
 <br>
    Output into table...<p id="demo"></p>

JS

(document).on("keyup", calculate());

function validateForm(){
  var validation = true;
  validation &= calculate();
  validation &= pmt();
  return validation;
}

function calculate() {
  var p = document.querySelector("#loan").value;
  var y = document.querySelector("#years").value;
  var rate = document.querySelector("#rate").value;
  var r = rate / 100 / 12;
  var n = y * 12;

  var I = (p * r);
  var monthlyPayment = -pmt(r,n,p);
  var mr = (monthlyPayment - I);
  var ti = (monthlyPayment) * n - p;
  var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);

  document.querySelector("#interest").value = I.toFixed(2);
  document.querySelector("#totalInterest").value = ti.toFixed(2);
  document.querySelector("#capitalRepayment").value = mr.toFixed(2);
  document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
  document.getElementById("demo").innerHTML = list;
}

function pmt(rate,nper,pv) {
    var pvif, pmt;

    pvif = Math.pow( 1 + rate, nper);
    pmt = rate / (pvif - 1) * -(pv * pvif);   

    return pmt;
}

function computeSchedule(loan_amount, interest_rate, payments_per_year,     years, payment) {
    var schedule = [];
    var remaining = loan_amount;
    var number_of_payments = payments_per_year * years;

    for (var i=0; i<=number_of_payments; i++) {
        var interest = remaining * (interest_rate/100/payments_per_year);
        var principle = (payment-interest);
        var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
        schedule.push(row);
        remaining -= principle
    }

    return schedule;
}

回答1:


the above answer is right but if concern about performance do insert html outside loop

var list = computeSchedule(p, rate, 12, y, monthlyPayment);
var tables = "";
for (var i = 0; i < list.length; i++) {
  tables += "<tr>" +
    "<td>" + list[i][0] + "</td>" +
    "<td>" + list[i][1] + "</td>" +
    "<td>" + list[i][2] + "</td>" +
    "<td>" + list[i][3] + "</td>" +
    "<td>" + list[i][4] + "</td>" +
    "</tr>";
}
document.getElementById("demo").innerHTML = '<table>' + tables + '</table>';



回答2:


I am not sure if I understand you correctly, but this should normally be the solution. You're fiddle printed some js errors, I haven't fixed them in this example.

function validateForm(){
  var validation = true;
  validation &= calculate();
  validation &= pmt();
  return validation;
}

function calculate() {
  var p = document.querySelector("#loan").value;
  var y = document.querySelector("#years").value;
  var rate = document.querySelector("#rate").value;
  var r = rate / 100 / 12;
  var n = y * 12;

  var I = (p * r);
  var monthlyPayment = -pmt(r,n,p);
  var mr = (monthlyPayment - I);
  var ti = (monthlyPayment) * n - p;
  var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);

  document.querySelector("#interest").value = I.toFixed(2);
  document.querySelector("#totalInterest").value = ti.toFixed(2);
  document.querySelector("#capitalRepayment").value = mr.toFixed(2);
  document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
  
  var list = computeSchedule(p, rate, 12, y, monthlyPayment);
  console.log(list.length);
  for (var i=0; i < list.length; i++) {
  	document.getElementById("test").innerHTML += "<tr><td>" + list[i][0] + "</td><td>" + list[i][1] + "</td><td>" + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>";
  }
}

function pmt(rate,nper,pv) {
    var pvif, pmt;

    pvif = Math.pow( 1 + rate, nper);
    pmt = rate / (pvif - 1) * -(pv * pvif);   

    return pmt;
}

function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
    var schedule = [];
    var remaining = loan_amount;
    var number_of_payments = payments_per_year * years;

    for (var i=0; i<=number_of_payments; i++) {
        var interest = remaining * (interest_rate/100/payments_per_year);
        var principle = (payment-interest);
        var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
        schedule.push(row);
        remaining -= principle
    }

    return schedule;
}
table {
  border-spacing: 0;
}

table td {
  border: 1px solid #666;
  padding: 0 3px;
}
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
    <label>Amount </label>
    <input type="textbox" id="loan" value="100000"><br>
    <label>Years</label>
    <input type="textbox" id="years" value="15"><br>
    <label>Rate (%)</label>
    <input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
    <input type="button" value="Calculate" id="btn"><br>
    <label>Monthly Repayment</label>
    <input type="textbox" id="monthlyRepayment"><br>
    <label>Monthly Interest Only</label>
    <input type="textbox" id="interest"><br>
    <label>Monthly Capital Repayment</label>
    <input type="textbox" id="capitalRepayment"><br>
    <label>Total Interest</label>
    <input type="textbox" id="totalInterest">
  </form>
</div>
<br>
<table id="test">

</table>



回答3:


The result of computeSchedule contains a two dimensional array. You should be able to loop through it with two nested for loops. Then you can compose your table.

Very simple example would look like this:

var demoList = computeSchedule(p, rate, 12, y, monthlyPayment);

var table = "<table>";

for (var rowIndex=0; rowIndex <= n; rowIndex++) {
  var row = "<tr><td>#" + rowIndex + "</td>";
  for(var colIndex = 0; colIndex < 4; colIndex++) {
      row += "<td>" + demoList[rowIndex][colIndex] + "</td>";
  }
  table += row + "</tr>";
}
document.getElementById("output").innerHTML = table + "</table>";

You can also try the life version here: https://fiddle.jshell.net/aua4g8e7/



来源:https://stackoverflow.com/questions/44686291/js-how-to-output-values-from-function-into-html-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!