Value from Session Storage as a number? - 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 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.

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`

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

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?

Check if a value exists in two or more arrays [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 4 years ago.
I'm trying to check user input value against two or arrays to see if the value inputed by the user equals a value in one of the arrays. Based on which array the input value equals to, I want to display a specific alert message.
So far I have this:
var zip = document.getElementById('zip').value;
var zone1 = ['11220', '11223', '11224', '11225', '11226','11228'];
var zone2 = ['10038', '10001'];
So if the user enters ZIP code 11220, I would like to display a message: "Price: $50". If the user enters 10038, I would like the message "Price: $75".
What's the easiest and most efficient way to do this?
I had a similar task recently that I solved like this.
Adjust the code to do what you need to whatever element in the function passed to forEach.
var zone1 = ['11220', '11223', '11224', '11225', '11226','11228'],
zone2 = ['10038', '10001'],
zones = [[zone1, 50], [zone2, 75], ]
.map(([zone, price]) => [new Set(zone), price]);
var userValue = '11220';
zones
.filter(([zone, price]) => zone.has(userValue))
.map(([zone, price]) => price)
.forEach((price) => console.log(`Price: $${price}`))
var userValue = '10001';
zones
.filter(([zone, price]) => zone.has(userValue))
.map(([zone, price]) => price)
.forEach((price) => console.log(`Price: $${price}`))
//Handle bad values, too, by defining a function
function getPrices(value){
return zones
.filter(([zone, price]) => zone.has(value))
.map(([zone, price]) => price)
}
var someNonExistentValue = 'xxx';
results = getPrices(someNonExistentValue);
if (results.length){
results.forEach(foundItem => console.log(foundItem));
} else {
console.log('No items found!');
}
OUTPUT:
Price: $50
Price: $75
No items found!
You need to Google questions and try to form your own solution. Only when you have an persistent error in your code should you ask about it. Here's a freebie:
if(zone1.indexOf(zip)!==-1){alert("Price: $50");}
elseif(zone2.indexOf(zip)!==-1){alert("Price: $75");}
If you want most efficient, then you should not work with arrays, but with a plain object, keyed by the zip codes (or use a ES6 Map):
var zones = {
11220: 1, 11223: 1, 11224: 1, 11225: 1, 11226: 1, 11228: 1,
10038: 2, 10001: 2
};
var messages = ["Unknown", "Price $50", "Price $75"];
var zip = document.getElementById('zip');
var msg = document.getElementById('msg');
zip.oninput = function() {
msg.textContent = messages[zones[this.value] || 0];
};
Zip: <input id="zip">
<div id="msg"></div>
Try this
var zip = document.getElementById('zip').value;
var zone1 = ['11220', '11223', '11224', '11225', '11226','11228'];
var zone2 = ['10038', '10001']
if(zone1.includes(zip))
alert("Price: $50");
else if (zone2.includes(zip))
alert("Price: $75");
You can simply use Array.prototype.indexOf method to check if a value exists as an array element.
var zone1 = ['11220', '11223', '11224', '11225', '11226', '11228'];
var zone2 = ['10038', '10001'];
document.getElementById('zip').addEventListener('change', (e) => {
if (e.target.value.length === 5) {
if (checkExists(e.target.value, zone1)) {
console.log(`${e.target.value} found in zone1`);
} else if (checkExists(e.target.value, zone2)) {
console.log(`${e.target.value} found in zone2`);
} else {
console.log(`${e.target.value} not in any zone!`);
}
}
});
function checkExists(needle, haystack) {
return haystack.indexOf(needle) > -1;
}
Enter a zip code then click outside the textfield to validate<br>
<input id="zip" type="text">

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.

How to avoid having my localStorage variable over written

var s = 0;
btn.addEventListener('click', function() {
var ModelMake = prompt("Enter The Model Make"),
ModelYear = prompt("Enter The Model Year"),
Km = prompt("Enter The Amount Of Km"),
Price = prompt("Enter The Price"),
Status = prompt("Enter The Car's Status"),
FinalPrice,
Details = prompt("Enter the Details");
localStorage.setItem(s += 1, JSON.stringify({
ModelMake: ModelMake,
ModelYear: ModelYear,
Km: Km,
Price: Price,
Status: Status,
Details: Details,
FinalPrice: FinalPrice
}));
How do i avoid having my previous localStorage objects overwritten after the user REFRESHES or CLOSES the browser. The reason i capitalized is to emphasize that this code works and keeps generating different objects by incrementing as long as the user doesn't refresh or close the browser. the moment you refresh or reopen the application then enter new values the previous objects get overwritten with the new ones and the incrementation starts all over from 1 (overwriting the previous 1).
Try this.
I've created a new variable index which store the value of s at the end of each run.
This value is read while initializing s the next time user opens the page, so that you can continue where you left off.
var s = 0; // Problem lies here
if(typeof(Storage)!=="undefined")
{
s = parseInt(localStorage.getItem("index"));
}
btn.addEventListener('click', function() {
var ModelMake = prompt("Enter The Model Make"),
ModelYear = prompt("Enter The Model Year"),
Km = prompt("Enter The Amount Of Km"),
Price = prompt("Enter The Price"),
Status = prompt("Enter The Car's Status"),
FinalPrice,
Details = prompt("Enter the Details");
localStorage.setItem(s += 1, JSON.stringify({
ModelMake: ModelMake,
ModelYear: ModelYear,
Km: Km,
Price: Price,
Status: Status,
Details: Details,
FinalPrice: FinalPrice
}));
localStorage.setItem('index', s);
});
You can get the values first on app load and create.
Actually rather than setting it to 0 initially, store that as 'index' in your localstorage. Then you can pick up where you left off

Categories

Resources