Reputation: 2201
Here is my code
if(jQuery.cookie("box1") == "close") {
jQuery("#box1").remove();
};
I already have individual cookies for each box. Now i want to check the cookies with jquery and remove the corresponding box if the cookie value is 'close'.
How can i make that code work with other boxes? .Other boxes have similar IDs (box2, box3) and there's a cookie for each one
Upvotes: 0
Views: 180
Reputation: 318302
I don't really think the cookie plugin has an option to iterate over cookies, but you could get all the set cookies yourself and just iterate over them to see if the value is close
, and then remove the corresponding element, something like :
function get_cookies() {
var cookies = { };
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}
return cookies;
}
var cookies = get_cookies();
for(var name in cookies) {
if (cookies[name] == 'close') jQuery("#"+name).remove();
}
Upvotes: 1
Reputation: 8280
Have a look at this jquery.cookie
plugin: jQuery.cookie.
It will allow you to get the required results using code similar to this:
if ($.cookie('box1') === 'close') {
$('#box').remove();
}
Alternatively what you could do, whilst still using this plugin, is have a JSON object stored in your cookie of boxes to hide, that way you could make it slightly more generic, and implement it with the following:
// assuming the cookie: boxes-to-hide is an array of string id ['box1', 'box2']
$($.cookie('boxes-to-hide')).each(function() {
// this will be the id of the box to hide
$('#' + this).remove();
});
Upvotes: 0