I am trying to make a cart using web storage in google chrome. I have too pages index.html and cart.html. I can set the values from index.html and get it from the same page. But when I move to cart.html, the stored values cant access there. Why it happens? I didn't get much tutorials about this. Please help.
My pages are
index.html
<html>
<head>
<title>Cart test</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
sessionStorage.setItem( "total", 10 );
var has_cart = 0;
if(sessionStorage.length > 1){
has_cart = sessionStorage.length -1;
}
console.log(sessionStorage);
$(window).ready(function(){
$('#cart-size').val(has_cart);
});
</script>
<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<button type="button" data-id="1" product="1" merchant="1" class="add-cart">Add 1</button>
<button type="button" data-id="1" product="2" merchant="1" class="add-cart">Add 2</button>
<button type="button" data-id="1" product="3" merchant="2" class="add-cart">Add 3</button>
<br /><br />
<input type="text" size="3" id="cart-size" />
<br />
<br />
<a href="cart.html">Go to cart</a>
</body>
</html>
cart.html
<html>
<head>
<title>Cart</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var has_cart = 0;
if(sessionStorage.length > 1){
has_cart = sessionStorage.length -1 ;
}
console.log(sessionStorage);
$(window).ready(function(){
$('#cart-size').val(has_cart);
});
</script>
<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<input type="text" size="3" id="cart-size" />
<br />
<br />
</body>
</html>
custom.js
$(function(){
$('.add-cart').on('click', function(e){
e.preventDefault();
var elm = $(this);
var id = elm.attr('data-id');
var product = elm.attr('product');
var merchant = elm.attr('merchant');
cart = {
item: product,
id: id,
mer: merchant
};
var jsonStr = JSON.stringify( cart );
var cartValue = sessionStorage.getItem( product+id+merchant );
var cartObj = JSON.parse( cartValue );
if(cartObj){
alert('Product already added to cart');
}
else
{
$('#cart-size').val(parseInt($('#cart-size').val())+1);
sessionStorage.setItem( product+id+merchant, jsonStr );
}
});
});
I can't figure out the issue as there is not much helpful documentation in the web. Someone please help. Thank you all in advance
sessionStorageworks like global variables. It loses its scope when you change page or close tab.Use
localStorageinstead.Read more details here.