Reputation: 1069
I just wanna check if a cookie exists, set/reset the cookie for 1 day, and delete the cookie when the window/tab is closed
I'm trying to do this in JavaScript, but hell JS is one dumbass language(I swear), add to that I'm stupid.
Anyways here's what i'm doing:
function checkcookie(name)
{
//Can't figure this one out
//I want to check wheather the cookie is set or not
//if yes
//{ reset cookie + ... }
//else
//{ set cookie + ... }
}
function setcookie(name,value,day)
{
var expireDate = new Date();
expireDate.setSeconds(expireDate.getSeconds()+day*24*60*60*1000);
document.cookie = name + "=" + value + ";path=/;expires=" + expireDate.toGMTString();
}
function delcookie(name)
{
setcookie(name,"",-1);
}
Any kind of answer is appreciated and thx in advance.
Upvotes: 2
Views: 11955
Reputation: 14312
You can test the Quirksmode code here: http://jsfiddle.net/67RFW/
The code is working so it must be something else causing your problem... so see what it does for you if you run it in jsfiddle.net - that might help determine if its a browser setting
Upvotes: 1
Reputation: 5462
Here, try it.
function checkcookie(name)
{
if (name!=null && name!="")
{
//reset cookie
cookie_value="test";
document.cookie=name + "=" + cookie_value;
}
else
{
//if there is no cookie, create a new one
cookie_value="test";
document.cookie=name + "=" + cookie_value;
}
}
function setcookie(name,day)
{
var expireDate = new Date();
expireDate.setSeconds((expireDate.getSeconds()+day*24*60*60*1000);
document.cookie = "Name=" + name + ";path=/;expires=" + expireDate.toGMTString();
}
function delcookie(name)
{
setcookie(name,"",-1);
}
Upvotes: 0
Reputation: 37516
Quirksmode.org has an excellent article on writing wrapper methods for interacting with document.cookie
(an inherently unfriendly object).
The article explains how to implement the following methods: readCookie
, createCookie
, and eraseCookie
.
From these methods, it's easy to implement your checkCookie
function, that is, if readCookie
returns null or not.
Here's your checkCookie
:
function checkCookie(name)
{
return readCookie(name) != null;
}
Here's the other three functions that the article provides:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var 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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
Upvotes: 6