0

Just started JS, have read a bunch of SO answers like this or this one or this other one, but still having trouble getting this to work. I have a list of inventory items, whenever one is clicked, I want the id of that one (stored as a data attribute) to be pushed to a sessionStorage cart object. Not functioning code below, comments show what the output is. It looks like I'm having a problem JSON.stringifying the array.

Help greatly appreciated.

    var cart = [];
    $(document).on("click", "#inventory", function() { // let's say i clicked on the #inventory whose data attribute for inventory_id is 13
      console.log($(this).data('inventory_id')) // outputs 13
      cart.push($(this).data('inventory_id')) 
    });
    console.log(cart) // outputs an array where Array[1] = 13 in last example
    console.log(JSON.stringify(cart)) // outputs a blank: []
    localStorage.setItem("cart", JSON.stringify(cart));
    console.log(localStorage.getItem("cart"))  // outputs a blank: []
Community
  • 1
  • 1
james
  • 3,989
  • 8
  • 47
  • 102
  • There's just one ***MAJOR*** flaw, ID's are **unique**, you can't have more than one element with the same ID. – adeneo Aug 23 '14 at 20:07
  • And, also, all your logic is outside the click handler, and happens on page load only, not when something is clicked ? – adeneo Aug 23 '14 at 20:09
  • no it all works fine, the logic is within the click handler, it's the `cart.push` line. Regarding the first issue, yes all of my IDs are unique – james Aug 23 '14 at 20:12
  • 1
    Put pushing to the array doesn't really do anything, other than pushing to the array, it doesn't update the storage or do anything else ? – adeneo Aug 23 '14 at 20:23
  • oh you're saying i need to move the local storage into the click handler i see, thanks! – james Aug 23 '14 at 20:30

1 Answers1

0

Per comments discussion, right answer was just to put the localStorage.setItem in the event handler itself.

var cart = [];
$(document).on("click", "#inventory", function() { // let's say i clicked on the #inventory whose data attribute for inventory_id is 13
  cart.push($(this).data('inventory_id'));
  localStorage.setItem("cart", JSON.stringify(cart));
});
james
  • 3,989
  • 8
  • 47
  • 102