0

I am developing a shopping cart system, where the user can add or remove products to his or her basket.

I am storing 2 things for each product in the product cookie: product barcode and price.

My code so far looks like this:

var addToBasketHandler = $(".add-product");
var removeFromBasketHandler = $(".unselect");

var Basket = {

    select: function (box, cookie) {

        box.addClass("selected");
        var ean = box.attr('ean');
        var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');

        if ($.cookie(cookie) == undefined) {
            $.cookie(cookie, ean + "~" + value);
        } else if ($.cookie(cookie).indexOf(ean) == -1) {
            $.cookie(cookie, $.cookie(cookie) + "|" + ean + "~" + value);
        }


    },

    deselect: function (box, cookie) {

        box.removeClass("selected");

        //  code to delete the cookie value

    }

};

$(document).ready(function () {

    $(addToBasketHandler).click(function () {

        var box = $(this).parents(".box-offer");
        Basket.select(box, "productCookie");

    });

    $(removeFromBasketHandler).click(function () {

        var box = $(this).parents(".box-offer");
        Basket.deselect(box, "productCookie");

    });

});

And after adding 3 products to my cart, my cookie looks like this:

productCookie = 9918430821007~12.00 | 7C9918430831006~3.00 | 7C7501031311309~50.30

Please help on how I could remove only the selected product from this cookie list above.

FYI I am using jquery + jquery cookie

CRABOLO
  • 8,605
  • 39
  • 41
  • 68
Wasiim
  • 146
  • 4
  • 16
  • http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery – ngonhan Mar 13 '14 at 06:32
  • Nope, that discussion is about changing the whole cookie value, whereas in my case i only need to know how to remove one value (barcode+ean) and the rest remains the same in the cookie :) – Wasiim Mar 13 '14 at 06:35

1 Answers1

1

Try

deselect: function (box, cookie) {
    box.removeClass("selected");
    var ean = box.attr('ean');
    var value = box.find($(".price strong")).html().replace(/[^0-9\.]/g, '');
    var val = ean + "~" + value; //value to be removed
    if ($.cookie(cookie) !== undefined) {
        var cookie_val = $.cookie(cookie);
        if (cookie_val.indexOf(val) !== -1) { //check value present in cookie
            var arr = cookie_val.replace(' ', '').split('|'); //remove spaces and split with |
            var index = arr.indexOf(val);//get index of value to be deleted
            arr.splice(index, 1); //remove value from array 
            $.cookie(cookie, arr.join(' | ')); //convert array to sting using join and set value to cookie
        }
    }
}
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107