MortenMoulder
MortenMoulder

Reputation: 6656

Add multiple values to cookie jQuery

<img src="http://website1.com/img.jpg" class="image" />
<img src="http://website1.com/img2.jpg" class="image" />
<img src="http://website1.com/img3.jpg" class="image" />
<img src="http://website1.com/img4.jpg" class="image" />

That is how my source code looks. I need to add the src value to the same cookie. My friend told me you could seperate it with a comma, but I'm not sure how I can do that with my code.

$(".image").click(function(){
    $.cookie("images", $(this).attr('src'), {expires: 9999999999});
}

That one works, but it will override the current cookie, which means I can only have 1 image in the cookie at the same time.

EDIT: I might as well tell you what I need it for. I need to extract the values from the images, and put them in img-tags.

.append('<img src=' + $.cookie("images") + ' />')

That's how I do it

Upvotes: 0

Views: 4370

Answers (1)

Khanh TO
Khanh TO

Reputation: 48982

$(".image").click(function(){
    $.cookie("images",$.cookie("images") + ","+ $(this).attr('src'), {expires: 9999999999});
}

When you want to append, do it like this:

var imgSrc = $.cookie("images").split(",");

for (var i=0;i<imgSrc.length;i++){
   if (imgSrc[i]!=""){
      .append("<img src='" + imgSrc[i] + "' />");
   }
}

Or

$.each($.cookie("images").split(","), function(index, value) {
   if (value !=""){
      .append("<img src='" + value + "' />");
   }
});

Upvotes: 2

Related Questions