menu

Questions & Answers

Why cookie is missing after page refresh

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>
Answers(1) :

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

Comments:
2023-01-21 23:10:05
there is no value in textbox after refreshing
2023-01-21 23:10:05
the value only changes when you change the value - ie the checkCookie function is called onchange ... if you want to check for a cookie on load use the body.onload event
2023-01-21 23:10:05
you are right, @ManseUK. If I would like to keep cookie value stay in the textbox after refreshing, What change should i do?
2023-01-21 23:10:05
@Acubi see my updated ... using the onload event of the body