I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;
Related
It's a pretty simple question and I'm going insane over here googling this all around and getting all these insanely non related answers.
here is the code:
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
var rez += key + " = "
obj.key + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja();">klikni</button>
<div id='div1'>xd</div>
Is it possible to pass an instance of an object "zut" to this function through HTML? If yes,how,if not,how am I supposed to do it through JS?
I want div1 html to be turned into:
boja = zuta
duzina = 12
thanks for answers
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = "+ obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(zut);">klikni</button>
<div id='div1'>xd</div>
You certainly can, although why your code doesn't work is because
1) - You're re declaring the variable rezand assigning to it using += which is no valid.
2) - obj.key is not valid, because there no such property called key, To access it you need to use brackets obj[key] nowkey will be considered as a variable and it's value will be used to get the property's value.
3) - You missed a + in this line var rez += key + " = " (HERE) obj.key + "<br/>";
4) - Your call to the method in the html is missing the argument.
you can either use onclick="fja(new Banana('zuta', 12));
Or declare the object inline in the HTML, or declare it in the js and pass it name
//in the Js
var zut = new Banana("zuta", 12);
//in the HTML
onclick="fja(zut);
Example one
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = " + obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(new Banana('zuta', 12));">klikni</button>
<div id='div1'>xd</div>
Example Two
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = " + obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(zut);">klikni</button>
<div id='div1'>xd</div>
I am working in a javascript function that takes all of the id's from a HTML table and sends each iteration of a loop and sends the info to a PLSQL procedure to update. I concat a number on each id to make each one unique. If I add an alert in the loop and click through one by one it works. If I let it go on its own with no alert it skips some iterations. Is there something that I am doing wrong?
function process_update() {
var nDataCount = document.getElementById("v_nDataCount").value;
var p_cc_no = document.getElementById("p_cc_no").value;
var p_orient = document.getElementById("p_orient").value;
var p_ot = document.getElementById("p_ot").value;
var p_buy = document.getElementById("p_buy").value;
var x = 0;
if (nDataCount == 0) {
x = 0;
} else {
x = 1;
}
for (i = nDataCount; i >= x; i--) {
var p_pc_no = ("p_pc_no[" + i + "]");
var p_pc_no2 = document.getElementById(p_pc_no).value;
var p_tm_name = ("p_tm_name[" + i + "]");
var p_tm_name2 = document.getElementById(p_tm_name).value;
var p_tm_no = ("p_tm_no[" + i + "]");
var p_tm_no2 = document.getElementById("p_tm_no").value;
var p_status = ("p_status[" + i + "]");
var p_status2 = document.getElementById(p_status).value;
var p_hrs_per_week = ("p_hrs_per_week[" + i + "]");
var p_hrs_per_week2 = document.getElementById(p_hrs_per_week).value;
var p_shift = ("p_shift[" + i + "]");
var p_shift2 = document.getElementById(p_shift).value;
var p_open = ("p_open[" + i + "]");
var p_open2 = document.getElementById(p_open).value;
var p_vacant = ("p_vacant[" + i + "]");
var p_vacant2 = document.getElementById(p_vacant).value;
var p_comments = ("p_comments[" + i + "]");
var p_comments2 = document.getElementById(p_comments).value;
var p_delete = ("p_delete[" + i + "]");
var p_delete2 = document.getElementById(p_delete).value;
window.location.href = "https://server.server.com/db/schema.package.p_process2?p_cc_no=" + p_cc_no + "&p_pc_no=" + p_pc_no2 + "&p_tm_name=" + p_tm_name2 + "&p_tm_no=" + p_tm_no2 + "&p_status=" + p_status2 + "&p_hrs_per_week=" + p_hrs_per_week2 + "&p_shift=" + p_shift2 + "&p_open=" + p_open2 + "&p_vacant=" + p_vacant2 + "&p_comments=" + p_comments2 + "&p_delete=" + p_delete2 + "&p_orient=" + p_orient + "&p_ot=" + p_ot + "&p_buy=" + p_buy + "";
}
Try the below code. I am using an AJAX GET request within the loop with request params, so as to not change the interface as much as possible. It uses only plain JS since I am not sure if you have jquery.
The actual changes start from line 48. Of course, I could test this code only in a limited way, so it might have possible bugs (please let me know). Also this can be possibly refined further, but as a quick fix it should do.
A word of caution: This could make a lot of calls in quick succession. So if you have too many loop iterations you might end up bringing down the server. Use wisely! :-) There should be some kind of batching to avoid this, but that will need the call interface to be changed.
Lines 48-61: I am creating a plain JS object out of all your parameters. The key is parameter name, value is the value to be passed.
Line 63: Here I am defining a self-invoking function, which makes the AJAX call in its body. This way, even though AJAX is asynchronous in nature, it will run in sync with the for loop outside.
Line 64-66: I am serializing the object created in the loop, into query parameters.
Lines 68,69: Framing the URL to which request will be made.
Lines 71-77: Actually making the request. This is just boilerplate AJAX-invoking code you can find anywhere (jQuery would've made life so much simpler :-)).
function process_update(){
var nDataCount = document.getElementById("v_nDataCount").value;
var p_cc_no = document.getElementById("p_cc_no").value;
var p_orient = document.getElementById("p_orient").value;
var p_ot = document.getElementById("p_ot").value;
var p_buy = document.getElementById("p_buy").value;
var x = 0;
if (nDataCount == 0) {
x = 0;
} else {
x = 1;
}
for (i = nDataCount; i >= x; i--) {
var p_pc_no = ("p_pc_no[" + i + "]");
var p_pc_no2 = document.getElementById(p_pc_no).value;
var p_tm_name = ("p_tm_name[" + i + "]");
var p_tm_name2 = document.getElementById(p_tm_name).value;
var p_tm_no = ("p_tm_no[" + i + "]");
var p_tm_no2 = document.getElementById("p_tm_no").value;
var p_status = ("p_status[" + i + "]");
var p_status2 = document.getElementById(p_status).value;
var p_hrs_per_week = ("p_hrs_per_week[" + i + "]");
var p_hrs_per_week2 = document.getElementById(p_hrs_per_week).value;
var p_shift = ("p_shift[" + i + "]");
var p_shift2 = document.getElementById(p_shift).value;
var p_open = ("p_open[" + i + "]");
var p_open2 = document.getElementById(p_open).value;
var p_vacant = ("p_vacant[" + i + "]");
var p_vacant2 = document.getElementById(p_vacant).value;
var p_comments = ("p_comments[" + i + "]");
var p_comments2 = document.getElementById(p_comments).value;
var p_delete = ("p_delete[" + i + "]");
var p_delete2 = document.getElementById(p_delete).value;
var dataObj = {p_cc_no:p_cc_no,
p_pc_no:p_pc_no2,
p_tm_name:p_tm_name2,
p_tm_no:p_tm_no2,
p_status:p_status2,
p_hrs_per_week:p_hrs_per_week2,
p_shift:p_shift2,
p_open:p_open2,
p_vacant:p_vacant2,
p_comments:p_comments2,
p_delete:p_delete2,
p_orient:p_orient,
p_ot:p_ot,
p_buy:p_buy};
(function(paramsObj){
var paramsStr = Object.keys(paramsObj).map(function(key) {
return key + '=' + paramsObj[key];
}).join('&');
var url = "https://server.server.com/db/schema.package.p_process2?";
url += paramsStr;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) {/*Handle Call Success*/};
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
})(dataObj);
}
}
Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length
My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}
tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
I'm trying to get and sort all the items in localStorage and output it to an HTML page.
This is what I'm doing:
<script>
function ShoppingCart() {
var totalPrice = 0;
var output;
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
var productName;
var productAlbum;
var productQuantity;
var productPrice;
var productSubTotal = 0;
var totalPrice;
productName = result.name
productAlbum = result.album;
productQuantity = result.quantity;
productPrice = parseFloat(result.price).toFixed(2);
productSubTotal = parseFloat(productQuantity * productPrice).toFixed(2);
outputName = "<div id='cart-table'><table><tr><td><b>NAME: </b>" + productName + "</td></tr></div>" ;
outputAlbum = "<tr><td><b>ALBUM: </b>" + productAlbum + "</td></tr>" ;
outputQuantity = "<tr><td><b>QUANTITY: </b>" + productQuantity + "</td></tr>";
outputPrice = "<tr><td><b>PRICE: </b> EUR " + productPrice + "</td></tr>";
outputSubTotal = "<tr><td><b>SUB-TOTAL: </b> EUR " + productSubTotal + "</td></tr></table><br><br>";
var outputTotal = "<table><tr><td><b>TOTAL:</b> EUR " + totalPrice + "</td></tr></table>";
var TotalOutput = outputName + outputAlbum + outputQuantity + outputPrice + outputSubTotal + outputTotal;
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
}
}
alert(TotalOutput);
}
window.onload = ShoppingCart;
</script>
The only item that is being output is the item named 'Proudct_0' in localStorage. Others are not being displayed!
This is what I have in localStorage: http://i.imgur.com/sHxXLOL.png
Any idea why this is happening ?
something wrong in your code.
What do you think if Product_0 not in the localStorage?
var product = localStorage.getItem('Product_'+i);
var result = JSON.parse(product);
may be null and throw an error.
Try this:
for (var i = 0; i < localStorage.length-1; i++){
var keyName = localStorage.key(i);
if(keyName.indexOf('Product_')==0) // check if key startwith 'Product_'
{
var product = localStorage.getItem(keyName);
//do your code here
}
}
Update
document.getElementById("Cart-Contents").innerHTML=TotalOutput;
it's replace, not append
Hope this help!