Javascript foreach (work out interest) - javascript

I'm trying to work out the interest of values that're inputed.
I ask for the principle rate, the rate in percentage and the number of years.
I want to figure out their simpleInterest and compundInterest.
I want it to display the result value for each year in a table.
I have a table that's getting the number of years when I type in the amount, for example 15. When I type in 15, it shows 15 rows but they're all the same.
I need it to work out the value for each year on a each row.
My current code is only showing 15 years as the same result.
My code :
<div class="container">
<div id="content">
<h2 class="interestOutput">Table for $<span id="interestPrinciple">Loading...</span> at <span id="interestRate">Loading...</span>%
</h2>
<table>
<tr>
<th>Year</th>
<th>SimpleInterest</th>
<th>CompoundInterest</th>
</tr>
<div id="tableResult">
</div>
</table>
</div>
<script type="text/javascript">
if (document.readyState = "complete") {
var principle = localStorage.getItem("principle");
var rate = localStorage.getItem("rate");
var years = localStorage.getItem("years");
var simple_interest = principle * (rate / 100) * years;
var compound_interest = principle * (1 + rate/100);
/*
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>';
*/
var tables = "";
for (var i = 0; i < years; i++) {
tables +=
"<tr>" +
"<td>" + years + "</td>" +
"<td>" + simple_interest + "</td>" +
"<td>" + compound_interest + "</td>"+
"</tr>";
}
document.getElementById("tableResult").innerHTML = '<table>' + tables + '</table>';
document.getElementById("interestPrinciple").innerHTML = principle;
document.getElementById("interestRate").innerHTML = rate;
//document.getElementById("gradeOutput").innerHTML = years;
}
</script>
I have now sorted the simple interest column but the compound column is not correct.
I was given this information : The formula to compute simple interest is interest = principal * (rate/100) * years. Just add the principal to the interest to generate the amount to display. The formula to compute compound interest is FinalAmount = principal * (1 + rate/100)Years. Notice that you do not need to add the principal in this case. Your program must read the principal amount, rate (%), and the maximum number of years (see Web Site Snapshots/Video below). Use the following messages to read the appropriate values:
My updated code is :
<div class="container">
<div id="content">
<h2 class="interestOutput">Table for $<span id="interestPrinciple">Loading...</span> at <span id="interestRate">Loading...</span>%
</h2>
<div id="tableResult"></div>
</div>
</div>
<script type="text/javascript">
if (document.readyState = "complete") {
var principle = localStorage.getItem("principle");
var rate = localStorage.getItem("rate");
var years = localStorage.getItem("years");
var tables = "";
for (var i = 0; i < years; i++) {
var simple_interest = principle * (rate / 100) * i;
var compound_interest = principle * (1 + (rate/100));
var final_simple = compound_interest + simple_interest;
var add_extra = 1 + (rate/100);
var final_compound = final_simple + add_extra;
tables +=
"<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>$" + final_simple + "</td>" +
"<td>$" + final_compound + "</td>"+
"</tr>";
}
document.getElementById("tableResult").innerHTML = '<table><tr><th>Year</th><th>SimpleInterest</th><th>CompoundInterest</th></tr>' + tables + '</table>';
document.getElementById("interestPrinciple").innerHTML = principle;
document.getElementById("interestRate").innerHTML = rate;
}
</script>

From what I can see, nothing about your iteration over the years is calling the problem solving functions. Your variables are declared once with the data available as is, and you're literally looping over the same data years amount of times.
Try something like this.
var tables, principle, years, rate, add_extra, times_compunded_per_tear, compound_rate, i;
principle = 10000;
years = 6;
rate = 5.6;
tables = '';
times_compounded_per_year = 12
compound_rate = 1 / times_compounded_per_year;
function simple_interest(currentYear) {
return principle * (rate / 100) * currentYear + principle;
}
function compound_interest(currentYear) {
return principle * (Math.pow(((1 + rate/100) / compound_rate), (compound_rate * currentYear)));
}
for (i = 0; i < years + 1; i++) {
tables +=
"<tr>" +
"<td>Year: "+ i +"</td>" +
"<td>Simple Interest "+ simple_interest(i).toFixed(2) + "</td>" +
"<td>Compound Interest "+ compound_interest(i).toFixed(2) + "</td>" +
"</tr>";
}
document.getElementById("tableResult").innerHTML = '<table>' + tables + '</table>';
document.getElementById("interestPrinciple").innerHTML = "Principle: "+principle;
document.getElementById("interestRate").innerHTML = "Interest Rate: "+rate;
//document.getElementById("gradeOutput").innerHTML = years;
<ul>
<li id="interestPrinciple"></li>
<li id="interestRate"></li>
</ul>
<div id="tableResult"></div>

Doing the same thing again and again will always give you the same results. In order for the results to change you need to use the index somewhere in your code.
Also why all the comments, clean your code, ask a precise question and you will get a precise answer.

You need to calculate the interest inside of the for loop otherwise you are just recycling the same variable each time and never updating it.
for (var i = 0; i < years; i++) {
var simple_interest = principle * (rate / 100) * i;
var compound_interest = principle * (1 + rate/100);
tables +=
"<tr>" +
"<td>" + (i + 1) + "</td>" +
"<td>" + simple_interest + "</td>" +
"<td>" + compound_interest + "</td>"+
"</tr>";
}
Also the compound_interest will need to use the index as well.

Related

Adapting a javascript class for interactive draggable pie charts on HTML5 canvas and integrate it in Webflow

I found this nice canvas pie on Github, but it's giving me some problem.
I'm not very good in JS, so I'm here asking for help.
https://github.com/jamesalvarez/draggable-piechart
In the example shown here, you can see a UI to manipulate the graphic.
https://codepen.io/Waterbear83/pen/vYOrbva?editors=0010
I don't understand how to display that UI even if I'm using the same js.
https://codepen.io/Waterbear83/pen/yLNqVBZ?editors=0010
Is there someone so nice to help?
Thanks!
function onPieChartChange(piechart) {
var table = document.getElementById("proportions-table");
var percentages = piechart.getAllSliceSizePercentages();
var labelsRow = "<tr>";
var propsRow = "<tr>";
for (var i = 0; i < proportions.length; i += 1) {
labelsRow += "<th>" + proportions[i].format.label + "</th>";
var v = "<var>" + percentages[i].toFixed(0) + "%</var>";
var plus =
'<div id="plu-' +
dimensions[i] +
'" class="adjust-button" data-i="' +
i +
'" data-d="-1">+</div>';
var minus =
'<div id="min-' +
dimensions[i] +
'" class="adjust-button" data-i="' +
i +
'" data-d="1">−</div>';
propsRow += "<td>" + v + plus + minus + "</td>";
}
labelsRow += "</tr>";
propsRow += "</tr>";
table.innerHTML = labelsRow + propsRow;
var adjust = document.getElementsByClassName("adjust-button");
function adjustClick(e) {
var i = this.getAttribute("data-i");
var d = this.getAttribute("data-d");
piechart.moveAngle(i, d * 0.1);
}
for (i = 0; i < adjust.length; i++) {
adjust[i].addEventListener("click", adjustClick);
}
}
[...] even if I'm using the same js
Not quite the same :) It misses this in your setup onchange: onPieChartChange
var newPie = new DraggablePiechart({
canvas: document.getElementById("piechart"),
data: data,
onchange: onPieChartChange
});
And then, after, in the onPieChartChange() there is also the dimensions (it's the same array but sorted randomly with the function knuthfisheryates2(), like you don't have this function in your code, it throws an error ReferenceError: dimensions is not defined because it does not exist) term to change in data in the function onPieChartChange(piechart). The same goes with proportions. But you can keep this one rather to replace it, it's handy to place common parameter like collapsed: false and to do operations on others like label: d.format.label.charAt(0).toUpperCase() + d.format.label.slice(1)
var proportions = data.map(function(d,i) { return {
label: d.format.label,
proportion: d.proportion,
collapsed: false,
format: {
color: d.format.color,
label: d.format.label.charAt(0).toUpperCase() + d.format.label.slice(1) // capitalise first letter
}
}});
function onPieChartChange(piechart) {
var table = document.getElementById("proportions-table");
var percentages = piechart.getAllSliceSizePercentages();
var labelsRow = "<tr>";
var propsRow = "<tr>";
for (var i = 0; i < proportions.length; i += 1) { // <------------------ HERE but keep --------
labelsRow += "<th>" + proportions[i].format.label + "</th>"; // <--- HERE but keep --------
var v = "<var>" + percentages[i].toFixed(0) + "%</var>";
var plus = '<div id="plu-' +
data[i] + // <----------------- HERE ------------------
'" class="adjust-button" data-i="' +
i +
'" data-d="-1">+</div>';
var minus =
'<div id="min-' +
data[i] + // <-------------- AND HERE -----------------
'" class="adjust-button" data-i="' +
i +
'" data-d="1">−</div>';
propsRow += "<td>" + v + plus + minus + "</td>";
}
labelsRow += "</tr>";
propsRow += "</tr>";
table.innerHTML = labelsRow + propsRow;
var adjust = document.getElementsByClassName("adjust-button");
function adjustClick(e) {
var i = this.getAttribute("data-i");
var d = this.getAttribute("data-d");
piechart.moveAngle(i, d * 0.1);
}
for (i = 0; i < adjust.length; i++) {
adjust[i].addEventListener("click", adjustClick);
}
}
Note: Couldn't make it works with the angles, I looked all his examples, he never uses it, he always uses proportions: proportions. So I just changed that in addition in your code.
The code is to large to be posted in a snippet here, here a codepen:
You can change the data from line 744 (see picture)
https://codepen.io/jghjghjhg/pen/rNVrwbd

Dynamic option list from an array

I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>

Unknown error when calling Array.length

first of all i need to say that i don't have much experience with JS. currently i'm trying to implement an web application with MVC framework. I'm in a work to develop an app that is also compatible with Internet explorer. in that case i'm using following JS method to populate a table which is working fine with all the browsers....
function populateTable(array) {
document.getElementById("instalationTable").style.display = "block";
var table = document.getElementById("ActivityDescription_installationID");
table.innerHTML = "";
elementsInTable = array;
var x = 0;
for (i = 0; i < (array.length * 2) ; i++) {
//alert(i);
if ((i % 2) == 0) {
//ID Row
var row = table.insertRow(i);
var cell_1 = row.insertCell(0);
cell_1.innerHTML = "<input type='text' disable='' class='form-control' value=" + array[x] + ">";
x = x + 1;
var cell_2 = row.insertCell(1);
cell_2.innerHTML = "<span class='btn btn-default' onclick='showEditRow(this)'><img src='../../Content/images/1414409386_48-24.png' /></span>";
var cell_3 = row.insertCell(2);
cell_3.innerHTML = "<span class='btn btn-default' onclick='removeRow(this)'>X</apan>";
}
else {
//Detail Row
var rowDetails = table.insertRow(i);
var cell = rowDetails.insertCell(0);
//cell.colspan = "3";
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
"<tr>" +
"<td><input type='checkbox' id='"+x+"_appServer'/> Application Server</span></td>" +
"<td>" +
"<select id='" + x + "_appServerVersion'>" +
"<option>Application version</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'><input type='radio' name='database' id='"+x+"_emptyDb' onChange='enableOptions(1)'/>" +
" Empty Database</br><input type='radio' name='database' id='" + x + "_instalationSlt' onChange='enableOptions(2)'/> Something Databse</td>" +
"</tr>" +
"<tr id='emptyDB'>" +
"<td>" +
"Oracle Version"+
"<select id='JS_OraVersion' name='" + x + "_oraVersion' style='width:100%'>" +
"<option>Ora version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Character Set" +
"<select id='JS_ChaSet' name='" + x + "_ChaSet' style='width:100%'>" +
"<option>Cha Set</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr id='dbImport'>" +
"<td>" +
"Something version" +
"<select id='JS_ImportVersion' name='" + x + "_ImportVersion' style='width:100%'>" +
"<option>Something version</option>" +
"</select>" +
"</td>" +
"<td>" +
"Something Charachter" +
"<select id='JS_ImportChaSet' name='" + x + "_ImportChaSet' style='width:100%'>" +
"<option>Something Cha</option>" +
"</select>" +
"</td>" +
"</tr>" +
"<tr>" +
"<td colspan='2'>" +
"Additional Requests </br>" +
"<textarea rows='4' id='" + x + "_specialReq' cols='37'> </textarea>" +
"<td/>"+
"</tr>"+
"</table>";
rowDetails.style.display = 'none';
Lock();
}
}
document.getElementById("instalationTable").style.display = "block";
}
i'm populating a form on the above table row, that collects some data to continue. to collect data i'm using following function which works fine with Google chrome but not with Internet explorer..
function getAllData() {
var StringtoSent = "";
for (i = 0; i < (elementsInTable.length) ; i++) {
var InsId = elementsInTable[i];
var _appServer = document.getElementById((i + 1) + "_appServer").checked;
var _appServerVersionDropDown = document.getElementById((i + 1) + "_appServerVersion");
var _appServerVersion = _appServerVersionDropDown.options[_appServerVersionDropDown.selectedIndex].value;
var _emptyDb = document.getElementById((i + 1) + "_emptyDb").checked;
var _instalationSlt = document.getElementById((i + 1) + "_instalationSlt").checked;
var _oraVersionDropDown = document.getElementsByName((i + 1) + "_oraVersion")[0];
var _oraVersion = _oraVersionDropDown.options[_oraVersionDropDown.selectedIndex].value;
var _ChaSetDropDown = document.getElementsByName((i + 1) + "_ChaSet")[0];
var _ChaSet = _ChaSetDropDown.options[_ChaSetDropDown.selectedIndex].value;
var _ImportVersionDropDown = document.getElementsByName((i + 1) + "_ImportVersion")[0];
var _ImportVersion = _ImportVersionDropDown.options[_ImportVersionDropDown.selectedIndex].value;
var _ImportChaSetDropDown = document.getElementsByName((i + 1) + "_ImportChaSet")[0];
var _ImportChaSet = _ImportChaSetDropDown.options[_ImportChaSetDropDown.selectedIndex].value;
var _specialReq = document.getElementById((i + 1) + "_specialReq").value;
StringtoSent = StringtoSent + "," + InsId + "," + _appServer + "," + _appServerVersion + "," + _emptyDb + "," + _instalationSlt + "," + _oraVersion + "," + _ChaSet + "," + _ImportVersion + "," + _ImportChaSet + "," + _specialReq + "|";
//return StringtoSent;
document.getElementById("ActivityDescription_instalationDetails").value = StringtoSent;
}
}
following image shows the error that im getting when it is ruining on VS 2012s IIS Express.
for (i = 0; i < (elementsInTable.length) ; i++) {
is the place that indicates as the error place . it always highlight the "elementsInTable.length" code segment.
Actually this error message elaborate nothing. i found some articles about the same error but occurring when trying to change the inner HTML of an element. but those solutions are not compatible for this situation.. Please help me with the problem
thanks in advance
Finally i found the Error
cell.innerHTML = "<table style='background-color:rgb(98, 98, 98);color:black;border- radius: 5px;' margin:2%; >" +
in above line i mistakenly added a CSS attribute "margin:2%;" in to a wrong place. Google chrome is intelligence enough to manage the situation and proceed the activity but Internet Explorer is not. as i found, this is the fact that prompt same error in different situations.
EG:
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
http://www.webdeveloper.com/forum/showthread.php?22946-innerHTML-amp-IE-Unknown-Runtime-Error
So if you got any unknown error in your Java Script code which uses "element.InnerHTML" or "document.Write" its better to check whether your tags are properly closed.
and i found several other situations that is generating same error
IE shows run time error for innerHTML
InnerHTML issue in IE8 and below
most of the times you can avoid this error by following W3C tag recommendations (http://www.w3.org/TR/html401/struct/global.html).

How to get size of array inside an json object

this is my json object
I need to get length of itemDetails array object,
I'm using
for (var i = 0; i < data[0].itemDetails.length; i++) {
itmCode = "it001";
itmName = "soap";
Qty = "4";
//netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
//paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
//balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + itmCode + "</td>" + "<td>" + itmName + "</td>" + "<td>" + Qty + "</td>" + "</tr>");
noOfItems = parseInt(noOfItems) + parseInt(Qty);
noOfProducts = parseInt(noOfProducts) + 1;
}
but always get 0 as length

Dynamically creating a table using JavaScript

I'm writing a script which creates a table with 4 columns. The columns are N, N * 10, N * 100 and N * 1000. I managed to create the first two columns, but now I'm stuck. How should I refactor my code?
var n;
var m1 = 10;
var m2 = 100;
var m3 = 1000;
document.writeln("<table>");
document.writeln("<h1>Calculating Compound Interest</h1>");
document.writeln("<thead><tr><th>N</th>");
document.writeln("<th>N * 10</th>");
document.writeln("<th>N * 100</th>");
document.writeln("<th>N * 1000</th>");
document.writeln("</tr></thead><tbody>");
for (var number = 1; number <= 5; number++) {
n = number * m1;
if (number % 2 !== 0)
document.writeln("<tr class='oddrow'><td>" + number +
"</td><td>" + n.toFixed(0) + "</td></tr>");
else
document.writeln("<tr><td>" + number +
"</td><td>" + n.toFixed(0) + "</td></tr>");
}
document.writeln("</tbody></table>");
change your for loop to following:
for ( var number = 1; number <= 5; ++number )
{
n = number * m1;
if ( number % 2 !== 0 )
document.writeln( "<tr class='oddrow'><td>" + number + "</td>");
else
document.writeln( "<tr><td>" + number + "</td>");
document.writeln("<td>" + n.toFixed(0) + "</td>" );
n = number * m2;
document.writeln("<td>" + n.toFixed(0) + "</td>" );
n = number * m3;
document.writeln("<td>" + n.toFixed(0) + "</td></tr>" );
}
You have to add two more td's where you will put the result of number*2 and number*m3
Also I would recommend you using innerHTML to write complete desired html rather than using document.writeIn every time
See The Solution on js fiddle
var n;
var m1 = 10;
var m2 = 100;
var m3 = 1000;
var heading_html = "<h1>Calculating Compound Interest</h1>" ;
var tbable_html = "<table border=1>";
tbable_html += "<thead><tr><th>N</th>";
tbable_html += "<th>N*10</th>";
tbable_html += "<th>N*100</th>";
tbable_html += "<th>N*1000</th>";
tbable_html +="</tr></thead><tbody>";
for (var number = 1; number <= 5; ++number) {
n1 = number * m1;
n2 = number * m2;
n3 = number * m3;
if (number % 2 !== 0)
tbable_html +="<tr class='oddrow'><td>" + number + "</td><td>" +
n1.toFixed(0)+"</td><td>"+n2.toFixed(0)+"</td><td>"+n3.toFixed(0)+"</td></tr>";
else
tbable_html +="<tr><td>" + number + "</td><td>" + n1.toFixed(0) +
"</td><td>" + n2.toFixed(0) + "</td><td>" + n3.toFixed(0) + "</td></tr>";
}
tbable_html +="</tbody></table>";
document.write(heading_html+tbable_html);
Try this:
var n = [1, 2, 3, 4, 5].reduce(function (string, n) {
return string + "<tr class='" + (n % 2 ? "oddrow" : "evenrow") + "'>" +
[n, 10 * n, 100 * n, 1000 * n].reduce(td, "") + "</tr>";
}, "");
document.body.innerHTML += "<table><thead><tr>" +
"<th>N</th><th>N * 10</th><th>N * 100</th><th>N * 1000</th>" +
"</tr></thead><tbody>" + n + "</tbody></table>";
function td(string, n) {
return string + "<td>" + n + "</td>";
}
See the demo: http://jsfiddle.net/7uPVH/
If you don't want to use .reduce then you could rewrite the above code as follows:
var n = "";
for (var i = 1; i <= 5; i++) {
n += "<tr class='" + (i % 2 ? "oddrow" : "evenrow") + "'>";
n += "<td>" + i + "</td>";
n += "<td>" + 10 * i + "</td>";
n += "<td>" + 100 * i + "</td>";
n += "<td>" + 1000 * i + "</td>";
n += "</tr>";
}
document.body.innerHTML += "<table><thead><tr>" +
"<th>N</th><th>N * 10</th><th>N * 100</th><th>N * 1000</th>" +
"</tr></thead><tbody>" + n + "</tbody></table>";
See the demo: http://jsfiddle.net/7uPVH/1/

Categories

Resources