HTML5 local storage

One of my favourite features under HML5 storage is local storage and session storage; both of these types of storage fall under the umbrella of web storage. Before these two features came along, we had to use cookies or SQL database or some other form of storage to store data. Using html5 local storage allows us to store much more data on the client than cookies can store, and the data is never sent back to the server and is only accessed when we ask for it through scripts. The difference between local and session storage involves the scope of the storage. Data stored through html5 local storage is permanent; this means it does not expire and will remain in the user's browser until the user or we delete it. Html5 session storage is only available while the client's browser is open and the script that stored it is running, once closed all the data will be lost.

In this blog, I will discuss local storage and how to store the values of a shopping cart from one page to another. As you know, HTML is stateless, so once we complete a form on one page and move to another or refresh the page, all the information we entered is lost unless we store the data for later use. 

HTML5 local storage setting up

To set up the web storage, we need to write some JavaScript or JQuery depending on your preference that allows us to save the data to local storage. In this blog, I will be using jQuery and the code is below.

$(function () {
    $("#deleteLocalStorage").on("click", function(){
        //Clear all localStorage
        localStorage.clear();
        //Clear only totalPrice
        //localStorage.removeItem("totalPrice");
        location.reload();
    })
});
$(function () {
    var courierParam;
    var totalPrice;
    var totalItems;
    
    $("#addToLocalStorage").on("click", function(){
        localStorage.totalPrice = $("#totalPrice").val();
        localStorage.totalItems = $("#numberOfItems").val();
    });

    //Only allowing one checkbox to be checked
    $(":checkbox").each(function () {
        var $courier = $(this);
        $courier.prop("checked", localStorage[$courier.prop("id")] === "true");
    });
    
    $('input[type="checkbox"]').on("change", function() {
        $(`input[name="${this.name}"]`).not(this).prop("checked", false);
        
        $("input[name='courier[]']").each(function (index, obj) {
            if ($(this).prop("checked") === true) {
                courierParam = $(this).val();
                var $courier = $(this);
                localStorage[$courier.prop("id")] = $courier.is(':checked');
            } else {
                localStorage.removeItem(this.id);
            }
        });
        });
    
    //Check if totalPrice is in localStorage
    if(localStorage.getItem("totalPrice") === null)
        {
            $("#displayTotalPrice").text("Price cannot be found");
            
        }
    else {
        $("#displayTotalPrice").text("Total Price £" + localStorage.totalPrice);
    }
    
    
     //Check if totalItems is in localStorage
     if(localStorage.getItem("totalItems") === null)
        {
             $("#displayNumberOfItems").text("No Items found");
            
        }
    else {
        $("#displayNumberOfItems").text("Number of items" + " " + localStorage.totalItems);
        }
    });

I have 60 lines of code above, so let's explain what is going on.

Lines 1 to 9 remove items from the localstorage object when you click the button deleteLocalStorage, we can remove all items or just an individual item from localStorage.

Lines 15 to 18 add items to localStorage when you click the button addToLocalStorage.

Lines 20 to 38 check that only one checkbox from the checkbox group can be selected; these checkboxes are displaying the courier that will ship the product in the shopping cart. 

Finally lines 40 to 60 check to see if the localStorage has a value and then displays the appropriate text in the paragraph on the page.  

The HTML for the form is below, it has three courier checkboxes and two textboxes, in this example, the two text boxes are your shopping cart allowing you to enter the total price and number of items as you can see from the image.

HTML local storage

Once you select a courier and click submit, the form redirects to the results page which retrieves the values from localStorage and populates the checkbox and textboxes with your values.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>Code Examples</title>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <form id="form-one" class="text-center" method="post" action="ShowValuesOfLocalStorage.html">
        <p>Pleasee select a courier</p>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-DHL" name="courier[]"><label class="form-check-label" for="formCheck-1">DHL (£10.99)</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-DPD" name="courier[]"><label class="form-check-label" for="formCheck-3">DPD (£9.99)</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-Hermes" name="courier[]"><label class="form-check-label" for="formCheck-2">Hermes (£6.99)</label></div><input class="form-control" type="text" id="totalPrice" name="totalPrice" value="300.99">
        <input
            class="form-control" type="text" id="numberOfItems" placeholder="s" name="numberOfItems" value="4"><button class="btn btn-primary" id="addToLocalStorage" type="submit">Submit</button></form>
    <script src="/js/jquery-3.4.1.min.js"></script>
    <script src="/bootstrap/js/bootstrap.min.js"></script>
    <script src="/localStorage.js"></script></script>
</body>
</html>

Retrieving data stored

On the results page, the script above checks to see if the values added to localStorage exists and then returns the appropriate message as can be seen from the image below.

Retrieve localstorage

The HTML for the page can be found below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <title>Code Examples</title>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
    <form id="form-two" class="text-center">
        <p>Courier selected</p>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-DHL" name="courier[]"><label class="form-check-label" for="formCheck-1">DHL (£10.99)</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-DPD" name="courier[]"><label class="form-check-label" for="formCheck-3">DPD (£9.99)</label></div>
        <div class="form-check"><input class="form-check-input" type="checkbox" id="courier-Hermes" name="courier[]"><label class="form-check-label" for="formCheck-2">Hermes (£6.99)</label></div>
        <p id="displayNumberOfItems"></p>
        <p id="displayTotalPrice"></p><button class="btn btn-primary" id="deleteLocalStorage" type="button">Delete localStorage</button></form>
    <script src="/js/jquery-3.4.1.min.js"></script>
    <script src="/bootstrap/js/bootstrap.min.js"></script>
    <script src="/localStorage.js"></script></script>
</body>
</html>

As you can see, the values entered on the home page are added to localStorage. These values are then returned from localStorage on the next page, and all this took place on the client-side, now if you click the delete localStorage button, all the data will be deleted and the appropriate message displayed as the image below shows.

delete localstorage

Thank you for reading this blog. I hope you found it helpful in understanding local Storage.