Rbex Rbex - 1 month ago 9
Javascript Question

Adding localstorage array

I'm having hard time on this localstorage array. I have search it here but can't get it out. Hope you can help me with this one.

Here is my code.

$(function(){
var addWishlist = $('.add-wishlist');
addWishlist.click(function(e){
e.preventDefault();
var product_ids = [];
localStorage.setItem('product_ids', $(this).prev().val() );
console.log( localStorage.getItem('product_ids') );
});
});


The output is:
enter image description here

The output should be [2, 3, 4, 1]

Answer

You need to add it to array on button click and then store it to local storage. Also product_ids should be initialized outside the click event

var product_ids = [];
addWishlist.click(function(e){
        e.preventDefault();      
        product_ids.push($(this).prev().val())
        localStorage.setItem('product_ids',product_ids );
        console.log(localStorage.getItem('product_ids') );
    });