javascriptjquerycookiesjquery-cookie

If jQuery cookie index of


First, I found many topics on Google, but none of those solved my problem. I couldn't find a right solution to those topics.

Using jquery.cookie plugin and trying to make a bookmark system, I store each item id in a cookie like this:

$('.bookmarkAds').click(function () {
  var id = $(this).attr('data-id');
  if ($(this).hasClass('RedHeart')) {
    $(this).removeClass('RedHeart');
    $.removeCookie('Bookmark_' + id, id);
    $(this).attr('title', 'Add');
  } else {
    $(this).addClass('RedHeart');
    $.cookie('Bookmark_' + id, id, { expires: 3650 });
    $(this).attr('title', 'Remove');
  }
});

For example, these are user cookies:

Name: Bookmark_3017403 => Content: 3017403
Name: Bookmark_3217302 => Content: 3217302
Name: Bookmark_3217302 => Content: 2217312

Now I want to show bookmarked items in a page, want to get all cookies that contains Bookmark_, but I couldn't find the right solution. I tried:

if ($.cookie().indexOf('Bookmark_') > 1) {
}

or

if (document.cookie.indexOf('Bookmark_') == -1) {
    alert("1");
} else {
    alert("2");
}

but no success.

Goal: get all cookies that index of Bookmark_. Is it possible? Or did I do something wrong? Is there a solution?


Solution

  • To achieve this you need to loop over all the cookies set on the page and check them individually. Also note that when checking with indexOf a value of -1 means not found. 0 is a valid response that means the match was at the beginning of the string. Try this:

    $.each($.cookie(), function(k, v) {
      if (k.indexOf('Bookmark_') != -1) {
        console.log(k, v);
      }
    })
    

    Working example

    Note that I had to use jsFiddle for this example, as SO restricts cookie access in the snippets.