Pages

Saturday, April 9, 2011

Create cookie



<script type="text/javascript">
<!--

/* COOKIES */

var Cookies = {
init: function () {
var allCookies = document.cookie.split('; ');
for (var i=0;i<allCookies.length;i++) {
var cookiePair = allCookies[i].split('=');
this[cookiePair[0]] = cookiePair[1];
}
},
create: function (name,value,hours) {
if (hours) {
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
this[name] = value;
},
erase: function (name) {
this.create(name,'',-1);
this[name] = undefined;
}
};
Cookies.init();

function saveIt(name) {
var x = document.forms['cookieform'].cookievalue.value;
if (!x)
alert('Please fill in a value in the input box.');
else {
Cookies.create(name,x,1);
alert('Cookie created');
}
}

function readIt(name) {
alert('The value of the cookie is ' + Cookies[name]);
}

function eraseIt(name) {
Cookies.erase(name);
alert('Cookie erased');
}


var x = Cookies['jaycookie'];
if (x) alert('Cookie jaycookie \nthat you set on a previous visit, is still active.\nIts value is ' + x);


// -->
</script>


</head>

<body>

<form name="cookieform" action="#"><p>
The value of the cookie should be <input name="cookievalue" />
</p></form>

<p><a href="javascript:saveIt('jaycookie')" class="page">Create cookie 1</a><br />
<a href="javascript:readIt('jaycookie')" class="page">Read cookie 1</a><br />
<a href="javascript:eraseIt('jaycookie')" class="page">Erase cookie 1</a>.</p>

No comments: