skip to Main Content

I’m building shopping-cart-like feature with JQuery. So far I can add and remove items from the cart without a problem.

However, I would like the items in the list to persist if the user refreshes the page or decides to navigate away.

Here is a snippet of the functioning cart without any local storage.

$(document).ready(function() {
  $(".btn-primary").click(function(e) {
    $(this).toggleClass("btn-warning");
    toggleText($(this));

    if (!$(`li[data-attribute="${e.target.id}"]`).length) {
      addItem(e.target.id);
    } else {
      $(`li[data-attribute="${e.target.id}"]`).remove();
    }
    setBadge();
    $(".btn-danger").click(function() {
      removeItem($(this).parent("li"));
    });
  });
});

function removeItem(item) {
  $(`#${item.data("attribute")}`).removeClass("btn-warning");
  toggleText($(`#${item.data("attribute")}`));
  item.remove();
  setBadge();
}

function addItem(item) {
  $("ul").append(
    `<li class='well' data-attribute='${item}'>
       ${$(`.${item}-container p`).text()} 
       <button class='btn btn-danger'>-</button>
     </li>`
   );
}

function setBadge() {
  $(".badge").remove();
  $("h3").after("<span class='badge'>" + $("li").length + "</span>");
}

function toggleText(item) {
  if (item.hasClass("btn-warning")) {
    item.text("-");
  } else {
    item.text("+");
  }
}
h3 {
  display: inline;
}

.list-inline {
  padding: 3rem 0;
}

li.well {
  margin: 0 2rem;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="container">
  <div class="row">
    <div class="col-xs-3">
      <div class="well item-1-container">
        <p class="lead">
          Item 1
        </p>
        <button class="btn btn-primary" id="item-1">+</button>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="well item-2-container">
        <p class="lead">
          Item 2
        </p>
        <button class="btn btn-primary" id="item-2">+</button>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="well item-3-container">
        <p class="lead">
          Item 3
        </p>
        <button class="btn btn-primary" id="item-3">+</button>
      </div>
    </div>
    <div class="col-xs-3">
      <div class="well item-4-container">
        <p class="lead">
          Item 4
        </p>
        <button class="btn btn-primary" id="item-4">+</button>
      </div>
    </div>
  </div>
</div>

<hr />

<div class="container">
  <h3>The List </h3>
  <ul class="list-unstyled list-inline"></ul>
</div>

Here is a CodePen Demo of my attempt to incorporate local storage into the cart such that the items are stored. As you can see in the demo, it’s not working.

Can someone help me figure out what I’m doing wrong?

2

Answers


  1. I can tell you some steps for this.
    Firstly make an array of items for putting all added items in it.
    Write getLocalStorage/ setLocalstorage methods.
    On page load , check for the array of items, if it’s empty, do nothing and if it has some length, create dynamic template and append in the ul.

    While you add items in your function, keep adding the same in the array by push function and simultaneously set it to localstorage. Splice the array in case of remove item at proper index.

    You will get the solution. Please give it a try with above steps.

    Login or Signup to reply.
  2. Here you go with a solution https://codepen.io/Shiladitya/pen/VzpQzM?editors=1010

    $(document).ready(function() { 
      
      if(localStorage.getItem("cart") != null){
        var items = JSON.parse(localStorage.getItem("cart")).items;
        for(var i=0; i<items.length; i++){
          addItem(items[i]);
          $('#' + items[i]).toggleClass("btn-warning");
          toggleText(items[i]);
        }
        setBadge();
      }
      
      $(".btn-primary").click(function(e) {
        $(this).toggleClass("btn-warning");
        toggleText($(this).attr('id'));
    
        if (!$(`li[data-attribute="${e.target.id}"]`).length) {
          addItem(e.target.id);
        } else {
          $(`li[data-attribute="${e.target.id}"]`).remove();
        }
        setBadge();
        setLocalStorage(e.target.id, 0);
        $(".btn-danger").on('click', function() {
          removeItem($(this).parent("li"));
          setLocalStorage($(this).data('id'), 1);
        });
      });
      
      $(".btn-danger").on('click', function() {
        removeItem($(this).parent("li"));
        setLocalStorage($(this).data('id'), 1);
      });
    });
    
    function removeItem(item) {
      console.log(item);
      var id = item[0].attributes[1].value;
      $(`#${id}`).removeClass("btn-warning");
      toggleText(id);
      item.remove();
      setBadge();
    }
    
    function addItem(item) {
      $("ul").append(
            `<li class='well' data-attribute='${item}'>
    ${$(`.${item}-container p`).text()} 
    <button class='btn btn-danger' data-id='${item}'>-</button>
    </li>`
          );  
    }
    
    function setBadge() {
      $(".badge").remove();
      $("h3").after("<span class='badge'>" + $("li").length + "</span>");
    }
    
    function toggleText(item) {
      if ($('#' + item).hasClass("btn-warning")) {
        $('#' + item).text("-");
      } else {
        $('#' + item).text("+");
      }
    }
    
    
    var cart = {};
    cart.items = [];
    
    function setLocalStorage(id, flag) {
      if(flag) {
        cart.items.splice(cart.items.indexOf(id), 1);
      } else {
        cart.items.push(id);
      }
      console.log(JSON.stringify(cart));
      localStorage.setItem("cart", JSON.stringify(cart));
    }
    h3 {
      display: inline;
    }
    
    .list-inline {
      padding: 3rem 0;
    }
    
    li.well {
      margin: 0 2rem;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container">
      <div class="row">
        <div class="col-xs-3">
          <div class="well item-1-container">
            <p class="lead">
              Item 1
            </p>
            <button class="btn btn-primary" id="item-1" data-id="item-1">+</button>
          </div>
        </div>
        <div class="col-xs-3">
          <div class="well item-2-container">
            <p class="lead">
              Item 2
            </p>
            <button class="btn btn-primary" id="item-2" data-id="item-2">+</button>
          </div>
        </div>
        <div class="col-xs-3">
          <div class="well item-3-container">
            <p class="lead">
              Item 3
            </p>
            <button class="btn btn-primary" id="item-3" data-id="item-3">+</button>
          </div>
        </div>
        <div class="col-xs-3">
          <div class="well item-4-container">
            <p class="lead">
              Item 4
            </p>
            <button class="btn btn-primary" id="item-4" data-id="item-4">+</button>
          </div>
        </div>
      </div>
    </div>
    
    <hr />
    
    <div class="container">
      <h3>The List</h3>
      <ul class="list-unstyled list-inline"></ul>
    </div>

    Hope this will help you.

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