0

I am trying to remove a particular value from a cookie on a click event. My code sofar:

            $("a.js-delete-hotel").on("click", function (e) {
            e.preventDefault();                

            deleteHotelId =  $(this).attr("id");

                hotelIdsArray = $.cookie('hotel-comparison').split(/,/);

                if($.inArray(deleteHotelId, $.cookie('hotel-comparison').split(/,/))){
                    for(var i = hotelIdsArray.length-1; i--;){
                            if (hotelIdsArray[i] === deleteHotelId) hotelIdsArray.splice(i, 1);
                    }
                }

                $.cookie('hotel-comparison', hotelIdsArray);
        }); 

This code doesn't work. It creates another cookie with the same name and value.

Roman
  • 1,008
  • 1
  • 12
  • 28

3 Answers3

1

inArray() returns -1, if the item is not found in the array

$("a.js-delete-hotel").on("click", function(e) {
  e.preventDefault();

  var deleteHotelId = $(this).attr("id");

  var hotelIdsArray = $.cookie('hotel-comparison').split(/,/),
    idx = $.inArray(deleteHotelId, hotelIdsArray);

  if (idx > -1) {
    hotelIdsArray.splice(idx, 1);
  }

  $.cookie('hotel-comparison', hotelIdsArray.join());
});
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0

Use remove cookie

$.removeCookie('hotel-comparison');
madalinivascu
  • 30,904
  • 4
  • 32
  • 50
  • $.removeCookie will delete the cookie. What I need is to remove only some values in the cookie. – Roman Mar 29 '16 at 08:10
  • 1
    you remove the cookie and create a new one with the altered value – madalinivascu Mar 29 '16 at 08:11
  • Ok, so the cookie needs to be deleted first and then new one created with new values. I was just wondering if there was another way to do it without the need to delete the cookie. – Roman Mar 29 '16 at 08:17
0

You want to update the cookie with the new ID-array of values when one id is removed?

You should simply write the cookie again with the new value, as you are doing at the end.

Maybe it is more a problem with the removal of the id from the array? Have you debugged and verified the id is removed before the cookie is written again?

Regarding removal of items in array, maybe have a look at this: https://stackoverflow.com/a/3596096/2028628

Also this row:

if($.inArray(deleteHotelId, $.cookie('hotel-comparison').split(/,/))){

Can be changed to (as you set this value to hotelIdsArray in the row above)

if($.inArray(deleteHotelId, hotelIdsArray)){
Community
  • 1
  • 1
Martin
  • 83
  • 1
  • 7