Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cookies in javascript?

Status
Not open for further replies.

daveask

Programmer
Joined
Aug 11, 2004
Messages
108
Location
GB
Hi Experts,

Can you explain in delail how to set/get cookies by javascript?

Thank you in advance.
 
I'd suggest just playing around with them. That's what I did to learn them. I made this program (about as simple as you can get with cookies) using some cookie functions I found on the net.
Code:
<script language=javascript>
function getCookie(name) {
   var start = document.cookie.indexOf(name+"=");
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(";",len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function setCookie(name,value,expires,path,domain,secure) {
   document.cookie = name + "=" +escape(value) +
   ((expires) ? ";expires=" + expires.toGMTString() : "") +
   ((path) ? ";path=" + path : "") + 
   ((domain) ? ";domain=" + domain : "") +
   ((secure) ? ";secure" : "");
}

</script>

<body>
<form name=blahForm>
<script language=javascript>
var blah = getCookie("cookieTest");
var expireDate = new Date();
if (blah != null) {
   document.write("Welcome back " + blah + "<br><br>");
   expireDate.setTime(expireDate.getTime() - 1);
   document.write("<input type=button value='Destroy Cookie' onclick='setCookie(\"cookieTest\", \"\", expireDate);alert(\"cookie erased\");'><br><br>");
}
else {
   document.write("<input type=text name=blahText><br><br>");
   expireDate.setTime(Date.parse("01/06/2070"));
   document.write("<input type=button value='Remember Me' onclick='setCookie(\"cookieTest\", blahForm.blahText.value, expireDate);alert(\"cookie saved\");'><br><br>");
}
</script>
<input type=button value='Refresh Page' onclick='window.location.reload()'>
</form>
</body>

-kaht

banghead.gif
 
google:
cookies javascript introduction OR tutorial
 
kaht,

Thanks a lot. I have copied your code for study....but why you said "... just playing around with them ..."?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top