I'm trying to build something analogous to a shopping cart. On the page, a user can click any number of inventory
items, upon click, these items get added to sessionStorage
. On a different part of the page, I then show the sessionStorage
so that the user can modify the cart as needed.
Right now I have a problem where the sessionStorage
works in that it has all the data, but if I click a bunch of items, it's not until I refresh the page that I see the data reflected in my cart. This defeats the entire purpose of me trying to learn Javascript, so hoping there's an answer to allow auto-updates so a user can add to/remove from cart without page refreshes.
Code:
<body>
<div class="col-xs-2" id="cart">
</div>
</body>
<script>
var cart = [];
$(document).on("click", "#inventory", function() {
//if statement so that it pushes ONLY if it doesn't already exist in cart
cart.push({
inventory_id: $(this).data('inventory_id'),
inventory_name: $(this).data('inventory_name'),
inventory_description: $(this).data('inventory_description'),
lender_email: $(this).data('lender_email')
});
sessionStorage.setItem("cart", JSON.stringify(cart));
});
$('#cart').html(sessionStorage.getItem("cart"));
</script>
First you have to get the current state of the cart items so you can append on it, Otherwise you're replacing the same item.
You can view it live here: http://jsfiddle.net/1vfo2e0g/4/
<ul>
<li>
<a href="#" class="item"
data-inventory_id="1"
data-inventory_name="Item 1"
data-inventory_description="Description 1"
data-lender_email="email1@email.com">Item 1</a>
</li>
<li>
<a href="#" class="item"
data-inventory_id="2"
data-inventory_name="Item 2"
data-inventory_description="Description 2"
data-lender_email="email2@email.com">Item 2</a>
</li>
<ul>
<div class="col-xs-2" id="cart">
<ul></ul>
</div>
populateCart(); // Populates the cart when page loads
$(document).on("click", ".item", function() {
// Get current state of our items from session
var items = JSON.parse(sessionStorage.getItem("cart"));
if(items === null) // if cart is empty
items = [];
// Populate the item
var item = {
inventory_id: $(this).data('inventory_id'),
inventory_name: $(this).data('inventory_name'),
inventory_description: $(this).data('inventory_description'),
lender_email: $(this).data('lender_email')
};
items.push(item); // Push item to the cart
sessionStorage.setItem("cart", JSON.stringify(items)); // Save cart back to session
addToCart(item); // append item to the cart
});
function populateCart(){
var items = JSON.parse(sessionStorage.getItem("cart"));
if(items !== null){
var cart = $('#cart > ul');
for (i = 0; i < items.length; i++) {
cart.append('<li>' + items[i]['inventory_name'] + "</li>");
}
}
}
function addToCart(item){
$('#cart > ul').append('<li>'+ item['inventory_name'] +'</li>');
}