The cookie is set when user input value into the textbox.
However, the cookie is missing after page refresh.
Below is my code, can anyone help me?
<script type="text/javascript">
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;
}
function checkCookie()
{
var emailVal=getCookie("email");
if (emailVal!=null && emailVal!="")
{
document.getElementById('emailBox').value =emailVal;
}
else
{
var eVal = document.getElementById('emailBox').value;
setCookie("email",eVal,365);
}
}
</script>
<body>
<form>
<input type="text" id="emailBox" name="email" onchange="checkCookie()"/>
</form>
</body>
Works fine for me here -> http://jsfiddle.net/RAZZg/1/
The only thing that I think might be wrong is the placement of your JavaScript code ... try placing it either within the <body>
tags or add a <head>
tag :
<head>
// your code here
</head>
<body onload="checkCookie()">
</body>
Update : added the onload
attribute to the body tag to check the cookie on page load
checkCookie
function is called onchange
... if you want to check for a cookie on load use the body.onload
event onload
event of the body