Get best price on Unlocked Galaxy S10 Lite | ||||||||||||
|
||||||||||||
|
JavaScript: How to Work With Cookies (Part 2)Saving a CookieUse the setCookie JavaScript function to create a cookie and save a value to that cookie. Pass it three things: name, value and expires. The name is the name of the cookie you set. We will use it also when retrieving the cookie. The value is the information you want the cookie to save. Cookies dont like spaces, semi-colons, or commas, so we use the function escape(value) to encode the value. We will un-escape the value when retrieving the cookie. expires is when the cookie will expire (when it is be deleted
from the users computer). It is optional. If not used, the cookie expires when the user exits.
Putting together a basic setCookie function is quite easy.
<script language="JavaScript"><!--
function setCookie(name, value, expires) { document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString()); } Now, make the new Date object and set it 30 days ahead:
var exp = new Date(); //set new date object
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30)); //set it 30 days ahead Remember to close the script tag:
//-->
</script> So we can see it work, lets set our cookie with a button. We just set a cookie with the name myCookie and the value it is crunchy
Here is the HTML for the button and setting the cookie:
<form>
Note: the input tag is one line
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie','it is crunchy', exp)"> </form>
Related Links:
Cookie Central -- a site devoted completely to information about cookies.
|
privacy policy || © 1997-2016. astonishinc.com All Rights Reserved. |