I am trying to create a javascript basket for a prototype of the project I'm working on. I understand that in this situation, an MVC structure, such as Angular / Knockout, etc., would be absolutely perfect, but I'm still learning how to use it, so I cannot use them for this particular project. I also understand that I can support the server server board, but this is not an option in this scenario.
At the moment I have a list of html products, for example:
<ul id="products"> <li data-id="1" data-name="Product 1" data-price="10.00"> <input type="text" /><br /> <button>Add to cart</button> </li> <li data-id="2" data-name="Product 2" data-price="15.00"> <input type="text" /><br /> <button>Add to cart</button> </li> <li data-id="3" data-name="Product 3" data-price="20.00"> <input type="text" /><br /> <button>Add to cart</button> </li> </ul>
When loading the page, I create an empty "cart" object in localStorage as follows:
var cart = {}; cart.products = []; localStorage.setItem('cart', JSON.stringify(cart));
Then I attached the click event of the button element like this:
$('button').on('click', function(e) { var product = $(this).parent(); var quantity = $(product).find('input[type=text]').val(); // Ensure a valid quantity has been entered if (!isValidInteger(quantity) === true) { alert('Please enter a valid quantity'); return; } product.id = $(product).attr('data-id'); product.name = $(product).attr('data-name'); product.price = $(product).attr('data-price'); product.quantity = quantity; addToCart(product); });
Then I wrote the addToCart () function, which should take this product and try to insert it into the "products" array, which has the "cart" property:
function addToCart(product) { // Retrieve the cart object from local storage if (localStorage && localStorage.getItem('cart')) { var cart = JSON.parse(localStorage.getItem('cart')); cart.products.push(product); localStorage.setItem('cart', JSON.stringify(cart)); } }
This does not work, and I get an error message:
Uncaught TypeError: Converting circular structure to JSON
I do not understand where I am wrong, can anyone help?
And once this is resolved, I am a little confused about how I should maintain the condition of the cart. I was hoping that I would be able to store all the data in the "cart" object in localStorage, storing product identifiers, names, prices and quantities, and then reflecting this in the cart div inside the html. If items are added / removed, I update the "cart" object in local storage and then reflect the changes inside the html.
Is there an easier way to do this? I really could use some directions in the right direction.
Again, I understand that using Angular or even supporting the server side of the state would be the best solution, but for this project I can use jquery / javascript, so I need to work within my borders.
Thank!