js - how to output values from function into HTML table - javascript

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;
}

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>';

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>

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/

Related

Event if button is clicked as many times as you write in input

This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.

How can I calculate the interest over an amount of money using a for loop in Javascript?

When I try to calculate the interest over an amount of money put in, my script keeps calculating the interest over the starting balance. I'm trying to constantly calculate the percentage of interest over the new amount of money, using a for loop.
var btn = document.getElementById('btn');
var startBalance = document.getElementById('input1');
var percentage = document.getElementById('input2');
var output = document.getElementById('result');
btn.onclick = showBalance;
function showBalance() {
var interest = (startBalance.value / 100) * percentage.value;
var newBalance = +startBalance.value + interest;
var resultaat = "";
for (var i = 0; i <= 10; i++) {
resultaat += "Year " + i + ": €";
resultaat += newBalance.toFixed(2) + "<br>";
newBalance += interest;
}
output.innerHTML = resultaat;
}
Starting balance: <input type="text" id="input1">€ <br><br> Percentage of interest: <input type="text" id="input2">% <br><br>
<button id="btn">Calculate balance</button>
<p>New balances for the next few years:</p>
<p id="result"></p>
just redefining interest with newBalance as variable will solve your problem
for (var i = 0; i <= 10; i++) {
interest = (newBalance / 100) * percentage.value
resultaat += "Year " + i + ": €";
resultaat += newBalance.toFixed(2) + "<br>";
newBalance += interest;
}

javascript simple loop calculation

function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80
It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>

Adding Text Boxes With Javascript

I am working on some code that will add text boxes when a button is pressed.
the problems is when i fill out the info in the text box and then click add it deletes the content.
Im complacently new to java script so i don't know where i went wrong. It looks like its all correct to me.
var countBox = 1;
var boxName = 0;
function addInput() {
var boxName = "textBox" + countBox;
document.getElementById('responce').innerHTML += 'Opp Code <input type="text" onkeyup="checkvalue(this.id)" value="tes" id="opp_' + boxName + '"> ';
document.getElementById('responce').innerHTML += 'Item<input type="text" id="dec_' + boxName + '"> ';
document.getElementById('responce').innerHTML += 'Price<input type="text" id="pri_' + boxName + '"> <br>';
countBox += 1;
}
document.getElementById('responce').innerHTML += 'total<br><input type="text" id="total"> <br>';
function checkvalue(clicked_id) {
// var count = countBox - 1;
var textarea = document.getElementById(clicked_id);
var n1 = document.getElementById(clicked_id);
var opp = document.getElementById(clicked_id).value;
var dec = "dec";
var pri = "pri";
var res = clicked_id.substr(3);
var dec = dec + res;
var pri = pri + res;
if (opp == "wv") {
var description = "Wash & Vac";
var price = "12.99";
} else {
var description = "";
var price = "";
}
document.getElementById(dec).value = description;
document.getElementById(pri).value = price;
}
<input type="button" value="add" onclick="addInput()">
<p id="demo"></p>
<span id="responce"></span>
when you fill out the first box it should populate the other 2 boxes and then when you press add then there should be 3 more boxes and you should be able to do the same thing.
Yo should do it using insertAdjacentHTML function instead of innerHTML, like this:
let countBox =1;
let boxName = 0;
const $responce = document.getElementById('responce')
function addInput() {
let boxName="textBox"+countBox;
let template = ""
template += 'Opp Code <input type="text" onkeyup="checkvalue(this.id)" value="tes" id="opp_'+boxName+'"> ';
template += 'Item<input type="text" id="dec_'+boxName+'"> ';
template += 'Price<input type="text" id="pri_'+boxName+'"> <br>';
$responce.insertAdjacentHTML('beforeend', template);
countBox++;
}
// i don't know why this sentence is out of some function
/*document.getElementById('responce').innerHTML += 'total<br><input type="text" id="total"> <br>';*/
function checkvalue(clicked_id) {
// var count = countBox - 1;
var textarea = document.getElementById(clicked_id);
var n1 = document.getElementById(clicked_id);
var opp = document.getElementById(clicked_id).value;
var dec = "dec";
var pri = "pri";
var res = clicked_id.substr(3);
var dec = dec + res;
var pri = pri + res;
if (opp == "wv") {
var description = "Wash & Vac";
var price = "12.99";
} else {
var description = "";
var price = "";
}
document.getElementById(dec).value = description;
document.getElementById(pri).value = price;
}
<input type="button" value="add" onclick="addInput()"/>
<p id="demo"></p>
<span id="responce"></span>

Javascript textbox received as string

This is the Html form I use.
<form name="calculate" method="get" action="#" onsubmit="return Validate()">
<label>Enter a number</label>
<input id="numb1" name="numb1" id="numb2" placeholder="Number 1">
<label>Enter another number</label>
<input id="numb2" name="numb2" id="numb2" placeholder="Number 2">
<label>Result</label>
<textarea style="text-align:center; height:85px; max-height:85px;" name="summ" id="summ" disabled="disabled" placeholder="Result" dir="ltr"></textarea>
<br />
<input id="calc" name="calc" type="submit" value="Calculate!">
The JS
function Validate() {
if (calculate.numb1.value == "" || calculate.numb2.value == "") {
alert("Check the form again");
calculate.numb1.focus();
document.getElementById('summ').value = "";
return (false);
}
Update()
return (true);
}
function Update() {
var plus = calculate.numb1.value + calculate.numb2.value;
var minus = calculate.numb1.value - calculate.numb2.value;
var mult = calculate.numb1.value * calculate.numb2.value;
var div = calculate.numb1.value / calculate.numb2.value;
var multi = document.getElementById("summ").value = calculate.numb1.value + "+" + calculate.numb2.value + "=" + plus + "\n" + calculate.numb1.value + "-" + calculate.numb2.value + "=" + minus + "\n" + calculate.numb1.value + "*" + calculate.numb2.value + "=" + mult + "\n" + calculate.numb1.value + "/" + calculate.numb2.value + "=" + div;
}
All the calculations work perfectly accept the Plus function.
When you type 4+4 for example you get 44...
I tried parseFloat, but still, nothing changes.
var numb1 = parseFloat(document.calculate.numb1.value);
var numb2 = parseFloat(document.calculate.numb2.value);
var plus = numb1 + numb2;
var minus = numb1 - numb2;
var mult = numb1 * numb2;
var div = numb1 / numb2;
Convert them to numbers first.
Do this with every calculation with a string value.
var plus = Number(calculate.numb1.value) + Number(calculate.numb2.value);
Léon

Categories