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!

Array to Cookie

Status
Not open for further replies.

Michael42

Programmer
Oct 8, 2001
1,454
US
Hello, I have an array of about 20 string elements, what is the best way to write and retreive them from a cookie?

Please, please give an example.

Also, is there a maximum file size for cookies?


Thanks very much,

Michael
 
Check this link for max cookie size:

Here are functions to work with cookies:
Code:
function setCookie(name,value,daysTillExpires)
  {
  var name_value = name + "=" + escape(value);
  if (!daysTillExpires) daysTillExpires = "";
  else
    {
    var D = new Date();
    var mill = D.getTime();
    D.setTime(mill + Math.round(daysTillExpires * 86400000));
    daysTillExpires = "; expires=" + D.toGMTString();
    }
  var full = name_value + daysTillExpires;
  document.cookie = full;
  }

function killCookie(name)
  {
  var D = new Date();
  D.setTime(10);
  var full = name + "=; expires=" + D.toGMTString() + "; path=/";
  document.cookie = full;
  }

function getCookie(name)
  {
  if (document.cookie) var C = document.cookie;
  else return "";
  var pair = "";
  var arr = C.split("; ");
  for (var i=0;i<arr.length;i++)
    {
    if (arr[i].indexOf(name + &quot;=&quot;) == 0) pair = arr[i];
    }
  if (pair == &quot;&quot;) return &quot;&quot;;
  var result = pair.substring(pair.indexOf(&quot;=&quot;) + 1, pair.length);
  return unescape(result);
  }
Now, if you have an array you'd like to store, use something like this:
Code:
setCookie(&quot;storedArray&quot;,myArray.join(&quot;+&quot;));
The join() method puts the array into a single string separated by whatever is in the quotes.

Petey
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top