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



Solution 1:[1]

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?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 princess_hacker