Shawn31313
Shawn31313

Reputation: 6052

Deleting A Cookie

I'm creating an add [ITEM] feature to my site that will include cookies. Now the Add [ITEM] part works but I need an Remove [ITEM]. This is my code:

$(window).load(function(){
   function getCookie(c_name){
 var i,x,y,ARRcookies=document.cookie.split(";");
 for (i=0;i<ARRcookies.length;i++){
   x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
   y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
   x=x.replace(/^\s+|\s+$/g,"");
   if (x==c_name){
     return unescape(y);
     }}}
 function setCookie(c_name,value,exdays){
 var exdate=new Date();
 exdate.setDate(exdate.getDate() + exdays);
 var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
 document.cookie=c_name + "=" + c_value;
 }
     $(document).ready(function(){
var cookieyess=getCookie("save");
 if(cookieyess!==undefined&&cookieyess!==null&&cookieyess!==""){
$('#save1').show();
    }
    else{
 $('#save1').hide();
   }
 }); 
  $('#save_1').click(function(){
 var cookieyes=getCookie("save");
 if(cookieyes!==undefined&&cookieyes!==null&&cookieyes!==""){
$('#save1').show();
    }
    else{
 $('#save1').show();
        setCookie("save","yes",365);
    }
  });
});

Now I need to make a function so when you click Removes it deletes that Cookie.

Upvotes: 2

Views: 441

Answers (2)

Baz1nga
Baz1nga

Reputation: 15579

Here is a small library that I wrote:

var myCookieHandler = (function () {
    return {
        createCookie: function (name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        readCookie: function (name) {
            var nameEq = name + "=";
            var ca = document.cookie.split(';');
            var i;

            for (i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
                if (c.indexOf(nameEq) === 0) { return c.substring(nameEq.length, c.length); }
            }

            return null;
        },
        deleteCookie: function (name) {
            this.createCookie(name, null, -1);
        }
    };
}());

usage:

myCookieHandler .writeCookie("Login","true",2);

var cookieValue=myCookieHandler.readCookie("Login");

myCookieHandler.deleteCookie("Login");

Hope this helps..

Upvotes: 1

Sophie Alpert
Sophie Alpert

Reputation: 143134

To delete mycookie, this should work by setting an expiration date in the past:

setCookie("mycookie", "", -1)

Upvotes: 2

Related Questions