Home > database >  how do i update an html element with an item retrieved from localStorage?
how do i update an html element with an item retrieved from localStorage?

Time:10-30

I have a code with an html span that has a content of 0.00 and I want to update this span with an item from localStorage so I don't lose the data when reloading the page, I can rescue the item, but it disappears when I f5 on the page Does anybody know how to solve this?

my html code:

I have a button that when clicked should update the span with the item saved in localStorage

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products</title>
</head>
<body>
    

    <div>Products</div>
    <button><a href="/index.html">Products</a></button>
    <div data-js="value-cart-products">0,00</div>
    <button data-js="add-product">Add to Cart</button>

    <script src="./app.js"></script>
</body>
</html>

I can rescue the item from localStorage, but when I reload the page the item is lost.

my javascript code:

const addProducts = document.querySelector('[data-js="add-product"]')
const cartValue = document.querySelector('[data-js="value-cart-products"]')

let valueCartNumber = 1

let getNumber = JSON.parse(localStorage.getItem('number'))

let updateLocalStorage = ()=>{
    localStorage.setItem('number', JSON.stringify(valueCartNumber))
}

addProducts.addEventListener('click', ()=>{
    cartValue.innerHTML = getNumber;
})
updateLocalStorage()

CodePudding user response:

You can add an event when you refresh the page to check if something in localStorage exists. for example

if (localStorage.getItem(....)) {// update your variables here} 

CodePudding user response:

const addProducts = document.querySelector('[data-js="add-product"]');
const cartValue = document.querySelector('[data-js="value-cart-products"]');

const valueCartNumber = 1;

if (localStorage.getItem('number')) {
  cartValue.innerHTML = JSON.parse(localStorage.getItem('number'));
}

const updateLocalStorage = () => {
  localStorage.setItem('number', JSON.stringify(valueCartNumber));
};

addProducts.addEventListener('click', () => {
  updateLocalStorage();
});


    

First you check if the value is stored in the localstorage. If it is you populate the cartValue html node. On click you update the storage with the value contained in the constant valueCartNumber;

  • Related