Changing value in a cookie

Hi all,

I have a cookie that contains a name=value pair. I want to change the value. I can retrieve the value with the following code, but I do not know how to change it.

Thanks in advance.

function changeCookie() {
  var intStart = ((document.cookie.indexOf("CookieName=", 0)) + 12);
  if (intStart == -1)
  {
	alert('Cookie not found.');
	return null;
  }
  else
  {
	var intEnd = intStart + 11;
	var strCookie = document.cookie.substring(intStart, intEnd);
	if (strCookie == 'CookieValue')
	  return strCookie;
	else
	  return null;
  }
}

http://www.google.com/search?hl=en&lr=&ie=UTF-8&oe=UTF-8&safe=off&q=javascript+cookie+functions&spell=1

beetle,

Thanks for the help, but I already know how to use Google. :wink:

The issue I have is the cookie looks something like the following:

HTTP%5FUSER%5FAGENT=Mozilla%2F4%2E0+%28compatible%
3B+MSIE+6%2E0%3B+Windows+NT+5%2E1%3B+Q312461%3B+F%2D6%
2E0%2D20020225%29&Domain=domain;id=Pvs0vz77wV9wcm9mc3B3MkB3
ZWJmYXJYXJib3JuLmZvcmQuY29tAHJtb3JyaTc0ADELjMzLjUzAE5PTk9WVk
0ANTAwMUoxNTkyAD8AQQBOAElUAE1TWC5JTlRFUk5BVElPTkFMAElUADUyN
TEAQUxMRU4uUEFSSwBNSQBVU0EATlVMTC5jZW50b2tzAAAlkli3QFq7aPt0o
UTRvUIrPbWygrHxqcMoEeDu5B4gk54O3WQk33hthOEgH1PEUfdyBMek7i3ZIp
E0d0mckAjj&CookieName=CookieValue; SESSIONID=ADB0
934867FBED462278456

The name=value pair is set via ASP.

Writing a cookie with JavaScript is fairly straight forward, but in this case I need to be able to modify the value for the individual name=value pair.

If you can provide any more insight I would greatly appreciate it.

So, using the popular cookie functions, this doesn’t work?

setCookie( ‘SESSIONID’, ‘newValue’ );

or

var session = getCookie( ‘SESSIONID’ ):

???

Sorry - complex cookie issues are something I have no experience in

Great! I got it with your help beetle. Thank you very much. It was only one simple line of code, but I was having a brain dead session.

document.cookie = name=myCookie; CookieName=NewCookieValue;

The name myCookie was set via ASP, this was what was throwing me - how to reference the cookie and the the name=value pair.

Edit: Nope, it does not work. What is wrong?

If you’re cookie looks like this

name=myCookie; CookieName=NewCookieValue;

That’s actually TWO cookies. In otherwords, you have one cookie named “name” and another named “CookieName”.

Personally - I think the string format for cookies is horrible.

My cookie looks something like:

myCookie=Name1=Value1&Name2=Value2&CookieName=NewCookieValue&Name3=Value3&Name4=Value4;

So it is only one cookie.