Reputation: 4642
I have next code where I do:
Check if my cookie exist if it not exist then I create the cookie called value inside else I read the cookie again and check if value is 1, here i would like to set a new value but not change the expire date and time of this cookie only update the value
if( readCookie("value")==null)
{
createCookie("value",1,1);
}
else
{
if(readCookie("value")==1)
{
/*here I would like to set to cookie called value the new value to 2 */
}
else
{
alert("no es uno");
}
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Upvotes: 3
Views: 15356
Reputation: 144
While you can't directly check the expiry date, when you set the cookie up you can store the expiry date as part of the cookie. Then whenever you want to check the expiry date, you can look at that part of the cookie. And to change the cookie without affecting the expiry date, just recreate the cookie, replacing the expiry date.
document.cookie="username=John Doe Thu, 18 Dec 2013 12:00:00 UTC; expires=Thu, 18 Dec 2013 12:00:00 UTC";
You can always change the expiry date of the cookie when it is being created.
Upvotes: 2
Reputation: 3765
There is no way to get
expiration date of setted cookie in JavaScript, you can just get the value of cookie, so, I guess, without this knowledge you cant set cookie without replacing previous value of expiration.
Upvotes: 1