Reading and writing cookies using javascript
by ericbaumann
HTML
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie();"/>
</form>
<p id = 'cookieResult' >
</p>
JavaScript
<!--
function WriteCookie()
{
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + 'mine';
document.getElementById("cookieResult").innerHTML = "Setting Cookies : " + "name=" + cookievalue;
}
function ReadCookie()
{
var allcookies = document.cookie;
alert("All Cookies : " + allcookies);
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++){
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.getElementById("cookieResult").innerHTML = "Key is : " + name + " and Value is : " + value;
}
}
//-->