I'm trying to make a counter of the quantity of goods added to the basket.

This is a piece of block code that is output from the js file:

var sum={}; var cart={}; function goodsOut(data){ if(data!=0){ var pack=JSON.parse(data); console.log(pack); var out=""; out+='<div class="col-lg-12 single">'; for(var key in sum){ out+=`<div class="val-plus"><i data-id="${sum.key}" class="fas fa-plus"></i></div>`; } out+=`<a data-id="${pack.id}" class="ad-to-crt pull-right">Добавить в корзину</a>`; out+='</div>'; $('.goods-out').html(out); $('.val-plus').on('click', plusGoods); $('.ad-to-crt').on('click',addToCart); } 

With this function, I am going to sum the total id in the sum variable, and then when I click on the 'add to cart' button, the amount is transferred to the variable cart, to local storage.

  function plusGoods(){ var id = $(this).attr('data-id'); sum[id]++; } function addToCart(){ //добавляем товара в корзину var id=$(this).attr('data-id'); //console.log(id); if(cart[id]==undefined){ cart[id]=1;//если в корзине нет товара-делаем равным 1 } else{ cart[id]+=sum[id]; } saveCart(); showMiniCart(); } 

In these functions, I display and store the amount in local storage

  function loadCart(){ //проверяю есть ли в localStorage запись cart if(localStorage.getItem('cart')){ //если есть расшифровываю и записваю в перемунную cart cart = JSON.parse(localStorage.getItem('cart')); } saveCart(); } function saveCart(){ //сохраняю корзину в localStorage localStorage.setItem('cart',JSON.stringify(cart)); //корзину в строку } 

I just can’t understand why when I run a for key in sum loop, html doesn’t display this block at all, which is wrapped in a loop, maybe I’m not thinking right at all, and it’s not worth wrapping it in a loop. Help please, the task seems to be simple, but I can’t figure it out at all

  • and goodsOut when called? I suspect that the cart at this moment is just empty - Artem Gorlachev
  • goods out is called using another function that I didn’t show, I think it makes no sense, goods out is called when the page loads - Kirill Chetvertkov

0