skip to Main Content

I’m trying to create a shopping-car-function with a local storage which remembers the items in the shopping basket, but after reloading when i add or remove a item to the basket it start from 0 again.

let current = 0
let locstor = ''

function loadlocal() {
  let locstor = ''
  document.getElementById("basket").innerHTML = localStorage.getItem(locstor)
  locstor = localStorage.getItem(locstor)
  return locstor
}

function addItem() {
  current = document.getElementById("productStat").innerHTML = current + 1
  localStorage.setItem(locstor, current)
  document.getElementById("basket").innerHTML = localStorage.getItem(locstor)
}

function removeItem() {
  if (current < 1) current = 0;
  else
    current = document.getElementById("productStat").innerHTML = current - 1
  
  localStorage.setItem(locstor, current)
  document.getElementById("basket").innerHTML = localStorage.getItem(locstor)
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>Productpagina</title>
  <link href="buyingFunction.css" rel="stylesheet">


</head>

<body onload="loadlocal()">
  <p>
    <button onclick="removeItem()">-</button>
    <span id="productStat">&nbsp;0&nbsp;</span>
    <button onclick=addItem()>+</button>
  </p>

  <div>
    <button id="basket">0</button>
  </div>

  <script src="buyingFunction.js"></script>
</body>

</html>

I hope someone can explain me what i’m missing.

2

Answers


  1. The problem is how you are using the locstor variable. You declared the locstor variable twice, once outside the global scope and once inside the loadlocal function. This resulted in the global variable not being updated within the function and consequently you were using an empty local variable, which was not related to local storage and then you and tried to store and retrieve the values using the locstor variable, but it was not associating this with a specific key in local storage.

    To solve this you can remove the locstor variable because it is not necessary for your case and store the cart item counter in local storage with the key ‘basketCount. By doing this, when you load the page, you now retrieve the counter value from local storage using localStorage.getItem(‘basketCount’) and update the current variable with that value like this:

    // Initialize the 'current' variable with 0.
    let current = 0;
    
    function loadlocal() {
      // Retrieve the item count in the cart from local storage.
      current = parseInt(localStorage.getItem("basketCount")) || 0;
      
      // Update the content of the 'productStat' element to reflect the current count.
      document.getElementById("productStat").innerHTML = current;
      
      // Update the content of the 'basket' element to reflect the current count.
      document.getElementById("basket").innerHTML = current;
    }
    
    
    function addItem() {
      // Increment the current count.
      current++;
      
      // Store the new count in local storage.
      localStorage.setItem("basketCount", current);
      
      // Update the content of the 'productStat' element to reflect the current count.
      document.getElementById("productStat").innerHTML = current;
      
      // Update the content of the 'basket' element to reflect the current count.
      document.getElementById("basket").innerHTML = current;
    }
    
    
    function removeItem() {
      // Ensure that the count is not less than zero.
      if (current > 0) {
        // Decrement the current count.
        current--;
        
        // Store the new count in local storage.
        localStorage.setItem("basketCount", current);
      }
      
      // Update the content of the 'productStat' element to reflect the current count.
      document.getElementById("productStat").innerHTML = current;
      
      // Update the content of the 'basket' element to reflect the current count.
      document.getElementById("basket").innerHTML = current;
    }
    Login or Signup to reply.
  2. de-wilde,

    The localStorage object allows you to save key/value pairs in the browser which requires a Key name and the Value which we want to store for that key.

    localStorage.setItem(key, value);

    Example:

    localStorage.setItem("lastname", "Smith");
    localStorage.getItem("lastname");
    

    After analyzing your code, I got following things:

    1. You are using locstor as a key but you haven’t defined a name of that key. eg. lastname, username etc…
    2. In loadlocal() method you are trying to set the key name with blank string like let locstor = ''
    3. In loadlocal() method you are again trying to set the key name with getdata the key value which is making key name as ‘null’
      locstor = localStorage.getItem(locstor)
    4. You need another variable to store and retrieve basket value from localstorage.

    So, Please review below code along with the comment to explaing the changes which needs to be implemented and let me know if you need further help in that.

    let current = 0;
    
    // 1. This will be static the Key name.
    let locstor = 'basket'; 
    
    // 2. Variable to store and retrive updated or last saved value in localstorage
    // ====================
    let basketItems = 0; 
    
    function loadlocal() {
        // 3. Remove this line because store name (Key) can not be blank, null or empty
        // let locstor = '';
    
        document.getElementById("basket").innerHTML = localStorage.getItem(locstor);
    
        // 4. Retrive latest store value from localStorage and assign it to new variable instead of replacing it with key
        basketItems = localStorage.getItem(locstor);
    
        return basketItems;
    }
    

    enter image description here

    As stackoverflow snippet will not allow to access localStorage so I am sharing the full code below. I hope this will helpful.

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="UTF-8" />
      <title>Productpagina</title>
      <link href="buyingFunction.css" rel="stylesheet">
    
      <script>
        let current = 0;
    
        // 1. This will be static the Key name.
        let locstor = 'basket';
    
        // 2. Variable to store and retrive updated or last saved value in localstorage
        // ====================
        let basketItems = 0;
    
        function loadlocal() {
          // 3. Remove this line because store name (Key) can not be blank, null or empty
          // let locstor = '';
    
          document.getElementById("basket").innerHTML = localStorage.getItem(locstor);
    
          // 4. Retrive latest store value from localStorage and assign it to new variable instead of replacing it with key
          basketItems = localStorage.getItem(locstor);
    
          return basketItems;
        }
    
        function addItem() {
          current = document.getElementById("productStat").innerHTML = current + 1;
          localStorage.setItem(locstor, current);
          document.getElementById("basket").innerHTML = localStorage.getItem(locstor);
        }
    
        function removeItem() {
          if (current < 1) current = 0;
          else
            current = document.getElementById("productStat").innerHTML = current - 1;
    
          localStorage.setItem(locstor, current);
          document.getElementById("basket").innerHTML = localStorage.getItem(locstor);
        }
      </script>
    
    </head>
    
    <body onload="loadlocal()">
      <p>
        <button onclick="removeItem()">-</button>
        <span id="productStat">&nbsp;0&nbsp;</span>
        <button onclick=addItem()>+</button>
      </p>
    
      <div>
        <button id="basket">0</button>
      </div>
    
      <!-- <script src="buyingFunction.js"></script> -->
    </body>
    
    </html>
    

    Thanks,

    Jignesh Raval

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search