Question

I am storing the shopping cart items (json data) in cookie via jquery. I am able to add items to the cookie. Following is the javascript code.

$.cookie.json = true;
// empty cart
var emptydata = { "cartItems": [] };

var devicedata = new function (deviceId, qty) {
return { "deviceId": deviceId, "quantity": qty };
}


// to create json data
function createJSON(id, qty) {
    if (!$.cookie('devicelist')) {
      $.cookie('devicelist', emptydata);
    }
 devicedata.deviceId = id;
 devicedata.quantity = qty;
 cart = $.cookie('devicelist');
 cart.cartItems.push(devicedata);
 return cart;
}

// function to be called , when Add to cart button is clicked
function saveItems() {

   var deviceId = $('#lbldeviceId').html();
   var Qty = $('#txtQty').val();

   var jsondata = createJSON(deviceId, Qty);

   $.cookie('devicelist', jsondata);

}

sample json data

 { "cartItems": [
   {
     "deviceId": "1",
     "quantity": "1"
   },
   {
     "deviceId": "2",
     "quantity": "1"
   }
]}

How can i update the quantity of an existing device and remove an existing device in the cookie? Hope it can be done by looping through the items. If any other alternatives are there, please suggest me. Also is my approach good or should i go for some other approach?

Was it helpful?

Solution

Your approach seems to be right...

For updating and deleting items in the cart, you can use this code:

function modifyItem(deviceId, Qty)
{
    var cart_items = $.cookie('devicelist').cartItems;

    $(cart_items).each( function(i, v) {
      if (v && v.deviceId == deviceId) {      
      cart_items[i].quantity = Qty;   
      }
    });
    var obj = { "cartItems": cart_items };
    $.cookie('devicelist', obj);
}

function deleteItem(deviceId)
{
    var cart_items = $.cookie('devicelist').cartItems;

    $(cart_items).each( function(i, v) {
      if (v && v.deviceId == deviceId) {    
      cart_items.splice(i, 1);    
      }
    });
    var obj = { "cartItems": cart_items };
    $.cookie('devicelist', obj);
} 

Example of how to call them:

<a href="javascript:void(0);" onClick="javascript:modifyItem(3, 5);">Modify deviceId 3</a>
<a href="javascript:void(0);" onClick="javascript:deleteItem(4);">Delete deviceId 4</a>

EDIT:

As per OP's request in the comment, i modified the above functions:

function modifyItem(deviceId, Qty)
{
    cart = $.cookie('devicelist');  
    $(cart.cartItems).each( function(i, v) {
      if (v && v.deviceId == deviceId) {
        v.quantity = Qty;
        $.cookie('devicelist', cart);
      }
    });    
}

function deleteItem(deviceId)
{
    cart = $.cookie('devicelist');  
    $(cart.cartItems).each( function(i, v) {
      if (v && v.deviceId == deviceId) {
        cart.cartItems.splice(i, 1);
        $.cookie('devicelist', cart);
      }
    }); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top