Trying to write a basket and that is my question.

When you click the add to cart button, this code is triggered.

i++; total2.innerHTML = '(' + i + ')'; button.innerHTML = "Товар уже в корзине"; localStorage.setItem(i, productName); 

And here was the question, how do I calculate and display the quantity of goods in the basket? Those. when you click on a button, localStorage.setItem(1, productName); added to localStorage.setItem(1, productName); And when entering the page, how can I display the quantity of goods?

    2 answers 2

    Number of key / value pairs stored in localStorage

     localStorage.length 

    Both parameters of the setItem () method must be strings.

    • Do not tell the default localStorage.length is 1? - Goshka Tarasov
    • no, by default localStorage.length is 0, you can check it by clearing localStorage, using localStorage.clear () method - user205867
    • that's just the point, as soon as I set localStorage.clear () then localStorage.length is 0, as soon as I comment on the code and output it to the console of localStorage.length it becomes equal to 1 - Goshka Tarasov
    • surprisingly, I don’t have one, after I cleared localStorage, I deleted the cleanup code, leaving only the output alert (localStorage) with a comment, alert gave me 0, try another browser to test, maybe this is a bug in the browser - user205867
    • Well, look at krilof.bget.ru/e-store/ you can add any product to the cart and go to the cart, and the browser in one of the values ​​will give null - Goshka Tarasov

    You forward everything to the array => the array of parsys in json => json you throw in localstorage.

     var list = []; list.push({id: 5, 'name': 'someName5'}) list.push({id: 6, 'name': 'someName6'}) ... localStorage.setItem(1, JSON.stringify(list));` 

    If you need to count, you take out

     var itemsFromStorage = localStorage.getItem(1) // сейчас там строка console.log(JSON.parse(itemsFromStorage).length); // количество 
    • Well, if you need to write down, you take again from localStorage you write down a new element in an array, and you throw it back into localStorage - Vasily Barbashev
    • What is local storage? I recently toiled a similar task and had a lot of problems with cookies. I mean, what is the difference between cookies and this? - Telion
    • there is an API for managing, receiving / sending / clearing. But in general there is a sessionStorage - the data is stored until the browser is closed, and localStorage can only be deleted using javascript - Vasily Barbashev
    • I kind of asked about cookies ... They are also stored after closing, but for a specified period. How are they worse / better and when to use? - Telion
    • one
      can be deleted using js and has no expiration date + ready-made API of the browser itself. And cookies do not have an API, you need to do your read / write / delete methods. - Vasily Barbashev