Push array value in Localstorage

Posted on

Local Storage allow us to save key and value in a web browser. The data stored has no expiration date and will not be deleted even when the browser is closed. To remove the data is by simply using removeItem as below.

localStorage.removeItem("cart")

Below are the example of how we can implement LocalStorage to store Array of data.

<div class="product" onclick="cart('Samsung Note 10')">
  <p>Samsung Note 10</p>
  <p>Price: RM 2000</p>
</div>

<script>
function cart(a){
 var exphone = [];
 if(localStorage.getItem("cart") != undefined){
  exphone = JSON.parse(localStorage.getItem("cart"));
 }
 exphone.push(a);
 localStorage.setItem("cart",JSON.stringify(exphone));
}
</script>

To remove specific item in your Array, you can use splice. First we create a delete function so when the user click it will trigger the function. After we splice/delete elements, the array must be set again.

Right click your browser and choose inspect element. Go to the application tab to see the results.

Below are the full code that you can use and try them out:

  <div class="product">
      <div class="prod-list" onclick="cart('Samsung Note 10')">
        <p>Samsung Note 10</p>
        <p>Price: RM 2000</p>
      </div>
      <div class="prod-del">
        <button type="button" name="button" onclick="del('Samsung Note 10')">
        Delete from CART
       </button>
      </div>

      <div class="prod-list" onclick="cart('iPhone')">
        <p>iPhone</p>
        <p>Price: RM 5000</p>
      </div>
      <div class="prod-del">
        <button type="button" name="button" onclick="del('iPhone')">
       Delete from CART
        </button>
      </div>
    </div>

    <script>
     function cart(a){
       var exphone = [];
       if(localStorage.getItem("cart") != undefined){
         exphone = JSON.parse(localStorage.getItem("cart"));
       }
       exphone.push(a);
       localStorage.setItem("cart",JSON.stringify(exphone));
     }


     function del(b){
       var delphone = [];
       if(localStorage.getItem("cart") != undefined){
         delphone = JSON.parse(localStorage.getItem("cart"));
         var i = delphone.indexOf(b);
           if( i != null) {
             if(delphone[i] == b){
               delphone.splice(i, 1);
               localStorage.setItem("cart",JSON.stringify(delphone));
             }else {
               alert("There are no " + b + " in your cart");
             }

           } else {
             alert("There are no items in your CART");
           }
       }
     }
    </script>
Please follow and like us:

One Reply to “Push array value in Localstorage”

  1. whoah this weblog is great i love reading your articles.
    Keep up the great work! You realize, lots of individuals are hunting round for this info, you can help them greatly.

Leave a Reply

Your email address will not be published. Required fields are marked *