James James - 6 months ago 20
jQuery Question

jQuery checking localStorage and if empty / null to refresh an element

I have everything working on my cart so far, but when i click delete on the mini cart i cant seem to get it to check the localStorage and if empty array to reset a few elements... if i refresh the page it does change the cart count to 0 and the price to 0.00 but not updating when i click delete.... i have to refresh and struggling... hoping someone can help.

Delete action:

$(document).on('click', '.delete-item', function(event) {
event.preventDefault(); // disable normal link function so that it doesn't refresh the page

var item = $(this).data('item'); // get data item to delete
deleteItem(item);
$(".basket").hide();
});


Functions:

function deleteItem(index){
if (localStorage.basket) {
basket = JSON.parse(localStorage.basket);
basket.splice(index,1); // delete item at index
saveBasket();
updateBasket();
}

return;
}


save function:

// Save the basket
function saveBasket(){
if (window.localStorage){
localStorage.basket = JSON.stringify(basket);
}
}


update function:

function updateBasket(){
$.each(basket, function(product) {
//console.log(basket);
// update the basket count
//basket = JSON.parse(localStorage.basket);

//if(basket[product].qty === "0" || basket === null || basket.length === 0){
if(basket[product].qty === "0"){
$('.mini-cart .count').html("0");
} else {
$('.mini-cart .count').html(basket[product].qty); // set the cart amount
}

// update the basket total
if(basket[product].price > 0){
var finalPrice = basket[product].price * basket[product].qty; // calculate the price and how many
$('.mini-cart .price').html("£"+finalPrice);
} else {
$('.mini-cart .price').html("Basket is empty");
}
});

return;
}

Answer

You need to check if basket has length. If it does you enter the each loop, otherwise you would do whatever reset is needed.

function updateBasket(){
  if(!window.basket || !basket.length){
    // do reset
  }else{    
      $.each(basket, function(product) {...
  }
}