How to calculate and make the result be displayed on HTML? - javascript

I have two values on my html: "Money" and "Time", and those values come from Session Storage, depending on what the person filled previously on another html page. So lets say the person filled that they need to pay $100 in 2 days.
What i'm trying to do, is to create a list, showing the number of payments, with the amount to be paid in each payment. Like the example below
MONEY: $100 / TIME: 2 Days
RESULT:
$50
$50
So if the person has 5 days, instead of 2, it would appear as:
$20
$20
$20
$20
$20
For some reason, when i try my code at codepen, using random numbers instead of the values i have on Session Storage, it works just fine, but when using the numbers from Session Storage, the result is always the same: I have a <li> with just one "topic" like:
MONEY: $100 / TIME: 2 Days
RESULT:
$50
I read somewhere that it might be because my values where stored as strings, but i don't know if thats correct, nor do i know how to undo that.
Current code below:
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>
<script>
const displayMoney = document.getElementById("money-value");
const storedMoney = sessionStorage.getItem("Money")
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = sessionStorage.getItem("Time")
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
var calc = storedMoney / storedTime;
for (let i = 0; i < storedTime; i++) {
var list = document.createElement("li");
list.innerText = `${calc}`;
document.getElementById("payments").appendChild(list);
}

sessionStorage.getItem("Time")
will only return the first item that matches the selector. This is similar to document.querySelector("selector"), which will only return the first instance of a match with that selector, whereas document.querySelectorAll("selector") will give you all the elements with that selector.
getItem does not have such an All alternative.
Instead, use keys. Check out some solutions for your problem in this post (probably the easiest is the forEach): Javascript: Retrieve all keys from sessionStorage?

Related

looping over objects javascript

So recently I learned about using for in loops to loop over objects. We were given this problem to solve regarding a basic cart object that contains name of object and then quantity and price.
const cart = {
"Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 },
"Pink Bucket Hat": { quantity: 2, priceInCents: 1260 },
};
We have to write 2 functions, one that calculates total cost of inventory in cents and the other displays the inventory.
The calculateCartTotal function will take in the cart and return a total price, in cents, of everything inside of it.
The printCartInventory function will take in the cart and return a string, joined by \n, of the quantity and name of each item.
I was able to the finish question one with ease but am struggling with the 2nd one.
1st function:
function calculateCartTotal(cart) {
let total = 0;
for(let item in cart){
const product = cart[item]
const quantity = product.quantity
const price = product.priceInCents
total += quantity * price
}
return total
}
2nd function:
function printCartInventory(cart) {
let inventory = ""
for(let item in cart){
const product = cart[item]
const quantity = product.quantity
inventory += `${quantity}x${product}/n`
}
return inventory
}
When I test the 2nd function the autograder gives this error:
expected '2x[object Object]/n1x[object Object]/n1x[object Object]/n3x[object Object]/n' to include '2xCanvas Tote Bag\n1xBlack and White Chuck On Dress\n1xNatural Straw Wide Brim Hat\n3xBlue Stripe Casual Shirt'
When you look at the error message, note the part that says [object Object]. This is part of your code's output, and should ring a bell. It means your code tries to put an object in a string, instead of a string.
The guilty code is here:
inventory += `${quantity}x${product}/n`
product is not a string, but an object. It is not what you intended to output there. What you want to output is the name of the product, which is the key, not the value associated with that key. So it should be:
inventory += `${quantity}x${item}/n`

Iterating thorugh array but always returning last value

I am iterating thorugh an array and trying to get different data for each object in array but I end up with same data, if i have three products in billBodies i end up with three item that have the same value (for example i have 3 candies, 2 coffees, and 4 candy bars result I get is 4 candy, 4 candy, 4 candy).
Hope anyone can help i tried to search similar problems but didn't find it though...
for (let bill of dataOfBillHeader.billBodies) {
console.log(dataOfBillHeader)
console.log(this.productToShowOnView)
this.productToShowOnView.cipher = bill.product.cipher;
this.productToShowOnView.name = bill.product.name;
this.productToShowOnView.measure = bill.product.measure;
this.productToShowOnView.count = bill.product.count;
this.productToShowOnView.price = bill.product.price;
this.productToShowOnView.id = dataOfBillHeader.id;
this.productToShowOnView.count = bill.count;
this.productToShowOnView.quantity = bill.quantity;
this.productToShowOnView.discount = bill.discount;
this.productToShowOnView.discountAmount = bill.discountAmount;
this.productToShowOnView.totalPrice = bill.totalPrice;
console.log("to show on view is " + JSON.stringify(this.productToShowOnView));
const newBasket = this.productsInBasket;
this.productsInBasket.push(this.productToShowOnView);
this.productsInBasket = [...newBasket];
this.cd.detectChanges();
}
Well, you are just pushing the same object (reference) in there over and over, namely this.productToShowOnView. Why are you using this.productToShowOnView? Why not a local constant. And with a little magic you can make it a bit smaller, although I don't understand why you would go from one product data format to another one...:
const newBasket = [...this.productsInBasket];
for (let bill of dataOfBillHeader.billBodies) {
const product = {
// no need to get all those individually
...bill.product,
...bill,
//this is weird, all products have the same id?
id: dataOfBillHeader.id,
};
newBasket.push(product);
}
this.productsInBasket = newBasket;
this.cd.detectChanges();

Value from Session Storage as a number?

I have two values on my html: "Money" and "Time", and those values come from Session Storage, depending on what the person filled previously in another html page. So lets say the person filled that they need to pay $100 in 2 days.
So the idea would be for the result to be displayed on my HTML like:
$50
$50
If the number of days increased to 4, for example, the result would be:
$25
$25
$25
$25
When i hard code random numbers as the values for "Money" and "Time", the result is exactly what i need, just like the example above. But whenever i try to get the values from Session Storage, the result is always ONE topic of the <li> that i wanted to create, just like the example below:
Money: 100 / Days: 2
$50
My code so far:
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>
<script>
const displayMoney = document.getElementById("money-value");
const storedMoney = parseInt(sessionStorage.getItem("Money"));
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = parseInt(sessionStorage.getItem("Time"));
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
var calc = storedMoney / storedTime;
for (let i = 0; i < storedTime; i++) {
var list = document.createElement("li");
list.innerText = `${calc}`;
document.getElementById("payments").appendChild(list);
}
</script>
TL;DR
What i'm really struggling with, is to make the <li> display the payments in the same number of topics as the number of days.

How do i validate a users input based on a series of string i have assigned in JavaScript?

I am very new to JavaScript so please bear with me.
So i want to create multiple voucher codes and for each voucher code there is a specific redeemable amount attached to it. And if a user should buy a voucher and after getting the voucher code, inputs it in a textfield, how do i get JavaScript to validate the users voucher code and confirm the amount redeemed and print that out? Just like redeeming Amazon Giftcards!
I want all these done in a simple HTML file i have created.
Since am just starting out JS i can't seem to achieve this yet on my own.
for example i have several voucher codes in strings:
var voucher1 = AC60";
var voucher2= 'DC60';
var voucher3= 'RC60';
var voucher4= 'XC60';
var voucher5= 'YC60';
var voucher6= 'WC60';
var voucher7= 'ZC60';
How do i attach monetary value for each and validate a users input to confirm which has been redeemed and print out the value just like redeeming amazon giftcards?
What you're looking for is an Object or a Map. These data structures allow you to attach a monetary value to the voucher code in the form of a key-value pair (where the voucher code is the key and the monetary value is the value).
A simple example could work like this:
// This is a simple object literal of keys and values
const vouchers = {
AC60: 100,
DC60: 20,
RC60: 35,
XC60: 45,
YC60: 80,
WC60: 10,
ZC60: 200
};
// This function will update the ouput <div> with the voucher amount
// or indicate an unknown voucher was input
function getVoucherValue(event) {
const key = input.value; // Stores the value of the input
const value = vouchers[key]; // Looks up the key in the object
// If the key is valid, update the output <div> with the monetary value
// Else the key is undefined, update the output <div> with an error message
if (vouchers[key]) {
output.textContent = vouchers[key];
} else {
output.textContent = "Invalid voucher"
}
}
// Whenever the button is clicked, run the getVoucherValue() function
button.addEventListener("click", getVoucherValue);
<input id="input">
<button id="button">Get Voucher Value</button>
<div id="output"></div>
First a little note, as really you should not rely on javascript validation, if there is actual value attached to it, it would be far to easy to redeem whatever whenever.
Beyond that, yes, possible, so you would really want to start by creating a more "Complex" structure. Like an array, containing objects:
var myArray = [
{ code: "uniqueVoucher1", value: "10.00" },
{ code: "uniqueVoucher2", value: "20.00" },
]
Then you can use this array to "loop through" the data, for creating html... perhaps like this...
for (var i=0;i<myArray.length;i++){
document.write("<div>Code: " + myArray[i].code + ", Value: " + myArray[i].value + "</div>")
}
just a small example

Generating a price per item in an html table using a javascript

I have a javascript that is generating a table for me. The elements in the table are gathered in an array of arrays called sep. Sep contains 1152 sub arrays that are of the form:
Sep[0] //["316SS", "K", "-100 to 225°C", "Brass", "1/8", "4'", "4'", "8", "Ungrounded"]
So basically there are 1152 rows, each of which defines a products with 9 parameters. I want to make a for-loop that will create a price for each of the configurations. This is what I have so far:
//PART 1-------------WORKS FINE-----------------------------------
var eopartprice2 = []; //matrix that I want to contain my prices
for (var i = 0; i < sep.length; i++) {
strnum1 = sep[i][5]; //parameter 5 is a length of material
len1 = Number(strnum1.substr(0, strnum1.length - 1));
strnum2 = sep[i][6]; //parameter 6 is another length of material
len2 = Number(strnum2.substr(0, strnum2.length - 1));
strnum3 = sep[i][7]; //parameter 7 is the number of units required
condnum = Number(strnum3.substr(0, strnum3.length));
feetOfMat = len1*len2*condnum; //The product of these is the total feet of req material
//PART 2------------PFCost always = 0.87--------------------------
//Next i need to identify the cost of the material (to multiply by the total feet)
var costOfMat = [0.87, 0.87, 1.77, 0.55] //different costs of the 4 materials
if (sep[i][0] = "304SS") {
var PFCost = costOfMat[0]; //304SS costs 0.87/foot
} else if (sep[i][0] = "316SS") {
var PFCost = costOfMat[1]; //316SS costs 0.87/foot
} else if (sep[i][0] = "Inconel") {
var PFCost = costOfMat[2]; //Inconel costs 1.77/foot
} else if (sep[i][0] = "High Temp. Glass") {
var PFCost = costOfMat[3]; //High Temp. Glass costs 0.55/foot
}
baseMatCost[i] = PFCost*feetOfMat; //I'd like to generate a matrix that
//contains all of the base prices (1 for each row)
//PART 3---------------fitcost always = 36------------------------
//Trying to identify the cost of brass vs. stainless fittings
if (sep[i][3] = "Brass") {
fitcost = 36;
} else if (sep[i][3] = "Stainless Steel") {
fitcost = 37;
}
}
My Problem so far is that I want the prices to be defined based off of whether or not the if statements are satisfied but in both cases (fitcost and PFCost) the values are simply the ones defined in the first if statement.
Lastly I'd like to generate my final price in the eopartprice2 matrix based off adding up the materials generated above + some cost of labor multiplied by some margin.
Also I'm concerned with the speed of how quickly this runs as it will be a live table in my website, and every time I add more to this I feel like it's taking longer and longer to generate. Here's a link to my w3 that I'm working in.
Please, any help would be greatly appreciated :)
In your if statement conditions, you're using a single equals sign. This is an assignment operator, not a comparison operator!
So, an if statement such as if (sep[i][0] = "304SS") is actually assigning the value "304SS"; it is not comparing the value "304SS" to sep[i][0].
To correctly compare the values, you'll want to change the single equals sign to a double equals:
if (sep[i][0] == "304SS").
Note: == will convert types if necessary before comparing. For example: ".87" == 0.87 returns true.

Categories

Resources