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!

Cookie Basic Question

Status
Not open for further replies.

budapestnori

Technical User
Jan 15, 2004
33
HU
I want to set my first cookie, in it I want to store three items, color,bgcolor,color2. What is confusing me is would this need three cookies, one for each value? Or can I set them all in one cookie?

Thanks.
 
This is what I have been trying:

Set cookie(s):

var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear() + 1);
document.cookie = "bgcolor=" + x + ";expires=" + nextyear.toGMTString();
document.cookie = "color=" + z + ";expires=" + nextyear.toGMTString();

<script>
var allcookies = document.cookie;

var bg = allcookies.indexOf('bgcolor=');
var color = allcookies.indexOf('color=');

var start = bg + 8;
var start2 = color + 6;


var end = allcookies.indexOf(';',start);
var end2 = allcookies.indexOf(';',start2);


var value = allcookies.substring(start,end);
var value2 = allcookies.substring(start2,end2);

alert(value);
alert(value2);

</script>

But both alerts pop up with value for bgcolor???
 

You have two problems.

The first is that &quot;color&quot; is a substring of &quot;bgcolor&quot;, so your second indexOf statement picks up the first cookie, not the second. Changing &quot;color&quot; to &quot;fgcolor&quot; will solve this.

The second problem is that the second cookie doesn't have a &quot;;&quot; at the end, as it's the last value. Your code doesn't account for this.

Try the following as an alternative:

Code:
<html>
<head>
<script type=&quot;text/javascript&quot;>
<!--
var nextyear = new Date();
nextyear.setFullYear(nextyear.getFullYear() + 1);
document.cookie = &quot;bgcolor=#ffffff;expires=&quot; + nextyear.toGMTString();
document.cookie = &quot;fgcolor=#000000;expires=&quot; + nextyear.toGMTString();
var allcookies = document.cookie;

var startPos = allcookies.indexOf('bgcolor=') + 8;
var endPos = allcookies.indexOf(';', startPos);
var value = allcookies.substring(startPos, (endPos==-1)?allcookies.length:endPos);

var startPos = allcookies.indexOf('fgcolor=') + 8;
var endPos = allcookies.indexOf(';', startPos);
var value2 = allcookies.substring(startPos, (endPos==-1)?allcookies.length:endPos);

alert('bgcolor: ' + value);
alert('fgcolor: ' + value2);
//-->
</script>
</head>
<body></body>
</html>

Hope this helps,

Dan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top