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: []
5
  • There's just one MAJOR flaw, ID's are unique, you can't have more than one element with the same ID. Commented Aug 23, 2014 at 20:07
  • And, also, all your logic is outside the click handler, and happens on page load only, not when something is clicked ? Commented Aug 23, 2014 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 Commented Aug 23, 2014 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 ? Commented Aug 23, 2014 at 20:23
  • oh you're saying i need to move the local storage into the click handler i see, thanks! Commented Aug 23, 2014 at 20:30

1 Answer 1

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));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.