Srikanth Technologies

Cart with LocalStorage

In this blog, I show how to use localStorage feature of HTML5 to save Cart so that when user comes back to Cart page we load Cart from localStorage to retain cart data across page requests.

This is a single page application where cart is stored as a JavaScript array.

If we don't store cart data in localStorage, user loses cart data whenever he refreshes page as JavaScript array is lost everytime user page is loaded.

I use a simple HTML page with JavaScript, jQuery and localStorage feature of HTML5 to demostrate how to maintain a Cart and restore it when we come back to the page.

LocalStorage is one of the options provided by HTML5 under category Web Storage. Get more information about Web Storage here.

Load cart from Local Storage

The following code shows how to load cart data from local storage in document ready event of jQuery.

        var cart = [];  
        $(function () {
            if (localStorage.cart)
            {
                // load cart data from local storage
                cart = JSON.parse(localStorage.cart);  
                showCart();  // display cart that is loaded into cart array
            }
        });
    
The above code checks whether key cart is available in localStorage object. Object localStorage represents Local Storage feature of HTML5 and it stores data in the form of keys and values.

JSON.parse(string) is used to convert string form of cart to an array of JavaScript objects.

Add Item to Cart

The following code adds an item along with selected quantity to cart. Each item in the cart is a JavaScript object with Name, Price and Qty as properties.

At the end of adding item to cart, it displays cart and also saves it to local storage. Function saveCart() is used to save cart (an array of JavaScript objects) to local storage.

        function addToCart() {
            var price = $("#products").val();  // get selected product's price
            var name = $("#products option:selected").text();  // get product name
            var qty = $("#qty").val();  // get quantity

            // update Qty if product is already present
            for (var i in cart) {
                if(cart[i].Product == name)
                {
                    cart[i].Qty = qty;  // replace existing Qty
                    showCart();
                    saveCart();
                    return;
                }
            }

            var item = { Product: name,  Price: price, Qty: qty };
            cart.push(item);
            saveCart();
            showCart();
        }
    

Saving Cart to Local Storage

The following code is used to save cart to local storage. If localStorage object is not found in windows object then it does nothing as it means your brower is not supporting Local Storage feature.

JSON.stringify(object) is used to convert an array of JavaScript objects (cart) to JSON string before it is saved to localStorage.

        function saveCart() {
            if (window.localStorage)
            {
                localStorage.cart = JSON.stringify(cart);
            }
        }
    

Showing Cart

Code below displays cart object in the form of a table. It allows user to delete an item by clicking on Delete button.

         function showCart() {
            if (cart.length == 0) {
                $("#cart").css("visibility", "hidden"); // hide table that shows cart
                return;
            }

            $("#cart").css("visibility", "visible");
            $("#cartBody").empty();  // empty tbody of table 
            for (var i in cart) {
                var item = cart[i];
                var row = "<tr><td>" + item.Product + "</td><td>" +
                       item.Price + "</td><td>" + item.Qty + "</td><td>"
                       + item.Qty * item.Price + "</td><td>"
                       + "<button onclick='deleteItem(" + i + ")'>Delete</button></td></tr>";
                $("#cartBody").append(row);
            }
        }
    

HTML

The following HTML shows a dropdown list box of items and a textbox for quantity.

Select an item in the dropdown, enter quantity and click on Add To Cart button to add item to cart.


    <h2>Cart</h2>
    Select Product :
    <select id="products">
        <option value="50000">iPhone6</option>
        <option value="60000">iPhone6 Plus</option>
        <option value="45000">iPad Air 2 with Cellular</option>
    </select>

    Quantity :
    <input type="text" id="qty" size="3" />
    <p/>
    <button id="btnAdd" onclick="addToCart()" >Add To Cart</button>
    <p />
    <table id="cart" border="1" style="visibility:hidden; width:100%">
         <thead>
              <tr>
                  <th>Product</th>
                  <th>Price</th>
                  <th>Qty</th>
                  <th>Total</th>
                  <th></th>
             </tr>
         </thead>
         <tbody id="cartBody">

         </tbody>
    </table>

    

Complete Source Code

Here is the complete source of this example.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Shopping Cart</title>
    <style>
        td { text-align :center}
    </style>
    <script src="jquery-1.11.2.js"></script>
    <script>
        var cart = [];
        $(function () {
            if (localStorage.cart)
            {
                cart = JSON.parse(localStorage.cart);
                showCart();
            }
        });

        function addToCart() {
            var price = $("#products").val();
            var name = $("#products option:selected").text();
            var qty = $("#qty").val();

            // update qty if product is already present
            for (var i in cart) {
                if(cart[i].Product == name)
                {
                    cart[i].Qty = qty;
                    showCart();
                    saveCart();
                    return;
                }
            }
            // create JavaScript Object
            var item = { Product: name,  Price: price, Qty: qty }; 
            cart.push(item);
            saveCart();
            showCart();
        }

        function deleteItem(index){
            cart.splice(index,1); // delete item at index
            showCart();
            saveCart();
        }

        function saveCart() {
            if ( window.localStorage)
            {
                localStorage.cart = JSON.stringify(cart);
            }
        }

        function showCart() {
            if (cart.length == 0) {
                $("#cart").css("visibility", "hidden");
                return;
            }

            $("#cart").css("visibility", "visible");
            $("#cartBody").empty();
            for (var i in cart) {
                var item = cart[i];
                var row = "<tr><td>" + item.Product + "</td><td>" +
                             item.Price + "</td><td>" + item.Qty + "</td><td>"
                             + item.Qty * item.Price + "</td><td>"
                             + "<button onclick='deleteItem(" + i + ")'>Delete</button></td></tr>";
                $("#cartBody").append(row);
            }
        }
    </script>
</head>
<body>
    <h2>Cart</h2>
    Select Product :
    <select id="products">
        <option value="50000">iPhone6</option>
        <option value="60000">iPhone6 Plus</option>
        <option value="45000">iPad Air 2 with Cellular</option>
    </select>

    Quantity
    <input type="text" id="qty" size="3" />
    <p/>
    <button id="btnAdd" onclick="addToCart()" >Add To Cart</button>

    <p></p>
    <table id="cart" border="1" style="visibility:hidden; width:100%">
         <thead>
              <tr>
                  <th>Product</th>
                  <th>Price</th>
                  <th>Qty</th>
                  <th>Total</th>
                  <th></th>
             </tr>
         </thead>
         <tbody id="cartBody">

         </tbody>
    </table>

</body>
</html>
    

Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments