Reputation: 1539
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 should be [2, 3, 4, 1]
Upvotes: 0
Views: 334
Reputation: 44108
There a couple of things wrong:
product_ids
is always empty because you need to push()
or unshift()
, or anything to fill the array.localStorage
can only take strings, I don't even think it will even recognize your empty array.localStorage
push()
ed into the array productList
.productList
is updated, it is stored in a hidden input #cache
#cache
is converted into a string by JSON.stringify
.productList
is a string, it is then stored in localStorage
and is displayed in #output
.Due to SO sandbox, the Snippet doesn't work, so review this PLUNKER instead.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<fieldset>
<legend>wishList</legend>
<input id='in1'>
<button><a href='#' id='add'>Add</a>
</button>
<button><a href='#' id='done'>Done</a>
</button>
<label for='out1'>wishList:</label>
<output id='out1'></output>
<input id='cache' type='hidden'>
</fieldset>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var productList = [];
$('#add').on('click', function(e) {
e.preventDefault();
var productItem = $('#in1').val();
productList.push(productItem);
$('#cache').val(productList);
});
$('#done').on('click', function(e) {
e.preventDefault();
var cached = $('#cache').val();
var str = JSON.stringify(cached);
localStorage.setItem('proList', str);
var stored = localStorage.getItem('proList');
console.log(stored)
$('#out1').html(stored);
});
});
</script>
</body>
</html>
Upvotes: 0
Reputation: 222720
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') );
});
Upvotes: 1