The following script remembers values typed into a text box and populates a pre-defined div section with the cookie values. The values are hyperlinked to the same page.
The usage is simple:
window.onload = function(){cookies.init("cookieName", "textBoxName", "divId", 180)};
The cookies.init function accepts 4 parameters: a cookie name you want to use, the name of the input box used to enter values, the id of a div section that will hold cookie values, and cookie duration in days.
Here is the script:
var cookies = {
//the default value of the cookie life duration is set at 180 days
cookieLife : 180,
//arguments: cookie name
// input box name
// div id
// cookie duration in days
init:function( cookieName, textName, objId, cookieLife){
this.cookieName = cookieName;
this.fieldName = textName;
if(cookieLife){
this.cookieLife = cookieLife;
}
if(objId){
var obj = document.getElementById(objId);
if(obj)
obj.innerHTML = this.getCookieValues();
else
alert("Can not find object " + objId );
}
var frm = document.getElementsByTagName("form")[0];
frm.onsubmit = this.addString;
},
setCookie: function (value, expires, path, domain, secure) {
name= this.cookieName;
document.cookie =
name + "="
+ escape(value)
+ ((expires) ? "; expires=" + expires.toGMTString() : "")
+ ((path) ? "; path=" + path : "")
+ ((domain) ? "; domain=" + domain : "")
+ ((secure) ? "; secure" : "");
},
getCookie: function () {
var bites = document.cookie.split("; "); // break cookie into array of bites
for (var i=0; i < bites.length; i++) {
nextbite = bites[i].split("="); // break into name and value
if (nextbite[0] == this.cookieName) // if name matches
return unescape(nextbite[1]); // return value
}
return null;
},
addString:function (){
var field = eval ("document.forms[0]."+ cookies.fieldName);
if(typeof field == "undefined"){
alert("textName argument is undefined or \ntext input name is not valid");
return;
}
field.value = field.value.replace(/^\s*|\s*$/g,"");
var txtVal =field.value;
if(txtVal.length<1)
return;
var expires = new Date();
expires.setDate(expires.getDate() + cookies.cookieLife);
var contents= cookies.getCookie(cookies.cookieName);
if(contents != null && contents.length>0){
var vals = contents.split(".");
bFound = false;
for(var i=0; i<vals.length; i++){
if(vals[i]==txtVal){
bFound = true;
break;
}
}
if(!bFound)
contents+="."+txtVal;
}
else if(contents == null)
contents = txtVal;
cookies.setCookie(contents, expires,"/");
},
getCookieValues:function () {
var val = this.getCookie();
var html ='’;
if(val!= null && val.length>0){
var str = new String(val);
var aPr = str.split(".");
var pos=0;
if((pos = document.location.href.indexOf("?"))>-1)
var host = document.location.href.substr(0,pos);
else
var host = document.location.href;
var vHref = "<a href=’"+ host+"?" + this.fieldName+"=";
for(var i=0; i<aPr.length; i++){
html+= vHref+ aPr[i]+ "’>"+aPr[i]+"</a><br>";
}
}
return html;
}
}
