First we have some generic code that will set a cookie with a given name and value. In this example we've set the expiry date (when the cookie will be removed from your browser) to 30 days and all cookies will be set with a path value of '/' (the root level of the website):
var today = new Date(); var expiry = new Date(today.getTime() + 30 * 86400 * 1000); // plus 30 days function setCookie(name, value) { document.cookie = name + "=" + escape(value) + "; expires=" + expiry.toGMTString() + "; path=/"; }
Then comes the form handler function which is also quite simple. We first populate an associative array, prefs, with the selected name-value pairs and then loop through that array setting a cookie for each value:
var prefs = new Array(); function setPrefs(form) { prefs['fontfamily'] = form.fontfamily.options[form.fontfamily.selectedIndex].value; prefs['overflow'] = form.overflow.options[form.overflow .selectedIndex].value; for(var x in prefs) setCookie(x, prefs[x]); return true; }
A better approach is to use a single cookie to hold all the values rather then one for each. The reason for this is that browsers will only hold a certain number of cookies from a domain before they start deleting the oldest. They will also only hold a certain number of cookies in total. More on that later...
No comments:
Post a Comment