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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to Read and Write multiple Cookie variables

Cookies

How to Read and Write multiple Cookie variables

by  tlhawkins  Posted    (Edited  )
I've noticed many people asking questions about how to do a particular job with cookies. I've found these 2 functions very helpfull and I wanted to pass them on.

I adapted one of these from a book on javascript and I made the other one myself. I hope they work for you.
The idea is to be able to write more then one variable to a cookie and then retrieve them. I added the option of picking your own delimiter for multiple cookie variables because sometimes you may want to save text that has a common delimiter, or you may want to make a 3 demensional array in a cookie by changing the delimiter.

So here are the functions:

Code:
function readCookie(name,delimit)
{
  if (document.cookie == ')
  {
    return false;
  }
  else
  {
    var fC,lC;
	var mcookie = unescape(document.cookie);
	fC = mcookie.indexOf(name);
	var ph = fC + name.length;
	if ((fC != -1) && (mcookie.charAt(ph) == '='))
	{
	  fC += name.length + 1;
	  lC = mcookie.indexOf(delimit,fC);
	  if (lC == -1) lC = mcookie.length;
	  return unescape(mcookie.substring(fC,lC));
	}
	else
	{
	  return false;
	}
  }
}
function returns false if there was no cookie found with that name.

Here is the write cookie function. It's a little more complicated.

Code:
function writeCookie(name,value,delimit)
{
  if (document.cookie == ')
  {
    document.cookie = escape( name + "=" + value );
    return false;
  }
  else
  {
    var B4,Af,fC,lC;
	var mcookie = unescape(document.cookie);
	var ncookie;
	fC = mcookie.indexOf(name);
	var ph = fC + name.length;
	if ((fC != -1) && (mcookie.charAt(ph) == '='))
	{
	  B4 = mcookie.substring(0,fC);
	  fC += name.length + 1;
	  lC = mcookie.indexOf(delimit,fC);
	  if (lC == -1) lC = mcookie.length;
	  if (lC == mcookie.length)
	  {
	    ncookie = B4 + name + "=" + value;
	    document.cookie = escape(ncookie);
		return true;
	  }
	  else
	  {	
        Af = mcookie.substring(lC,mcookie.length);
		ncookie = B4 + name + "=" + value + Af;
		document.cookie = escape(ncookie);
		return true;
	  }	
	}
	else
	{
	  ncookie = mcookie + delimit + name + "=" + value;
	  document.cookie = escape(ncookie);
	  return false;
	}
  }
}

I hope these prove usefull to you.
If anyone has improvements on these scripts I would love to hear them.


Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top