Can anyone help me with this? I'm looking for a javascript that will add a cookie when the page loads, then read the cookies value whenever the user returns to that page, adding the coockie value to a hidden text field. I can do this with ASP, but the client's page is an HTML page that cannot be changed to an ASP page. Any help is greatly appreciated! Thank you.
you must use onload event in your page, if your page have multiple functions/events need to be loaded, let use this JavaScript, Multiple Functions onLoad & you can go to URLs below to learn how to use cookie with JavaScript: - JavaScript Cookies - Save and Restore Form Cookies - Cookie Enabled script - ... more
Here is the code for your functionality: <html> <head> <script language="javascript"> function createCookie(name,value,days) // fn. for creating cookies { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var flag = 0; var dcmntCookie = document.cookie.split(';'); // getting all cookies in the document and splitting them and storing in an array for(var i=0;i < dcmntCookie.length;i++) // looping through the cookies array { var ck = dcmntCookie[i]; while (ck.charAt(0)==' ') // loop for removing space at the begining { ck = ck.substring(1,ck.length); } if(ck) { cparts = ck.split('='); // splitting the cookie. eg: mycookie="some message" if (cparts[0]==name) { flag=1; document.getElementById('hiddenField').value=cparts[1]; //storing value of cookie to hidden field //alert(document.getElementById('hiddenField').value); break; } } } if(!flag) // if no such cookie exist, then create a new one createCookie(name,"cookie 4 the day",1); } </script> </head> <body onLoad="readCookie('MyCookie')"> <input type="hidden" id="hiddenField" name="hiddenField"/> </body> </html> Code (markup): Hope this helps.
I'll take a look thanks! The issue was never the cookie itself, it was populating the hidden textfield with the cookie value. Thanks again.