I am attempting to create something that will store a person's name and favorite color as cookies, and then display the person's favorite color if they have already entered it. This is the code:
<!DOCTYPE html>
function setCookie(Name, Color, exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(Color) + ((exdays==null) ? "" : ";expires=" + exdate.toUTCString());
document.cookie=Name + "=" + c_value;//stores cookie with format "(person's name)=(person's favorite color)"
function getCookie(user) {
var i,x,y,ARRCookie=document.cookie.split(";");//splits at each individual cookie so they can be considered one at a time
for (i=0;i<ARRCookie.length;i++) {
x=ARRCookie[i].substr(0,ARRCookie[i].indexOf("="));//the name of the cookie (what comes before "=")
y=ARRCookie[i].substr(ARRCookie[i].indexOf("=")+1);//the value of the cookie (what comes after "=")
if (x==user) {
return unescape(y);//if the name of the cookie matches the cookie requested, return its value
function checkCookie() {
var username=prompt('What is your name?','');//asks for your name to see if you have already created a cookie for yourself
var color=getCookie(username);
if (color!=null && color!="") {
document.write("Your favorite color is " + color + ".");//if cookie with given name exists, state its value
else {
var favcolor=prompt('What is your favorite color?','');
setCookie(username, favcolor, 365);
<body onload="checkCookie()"></body>
Interestingly, if, upon the prompt that asks for your name, you enter the name of the first cookie created for the page (e.g. if the first person to ever fill out set prompts to create a cookie was John and you entered John), the correct color will be returned from the function getCookie. However, if you enter the name of anyone else who has created a cookie on the page (e.g. if after John entered his data Lucy entered hers and you typed into the prompt box for your name "Lucy"), it will prompt you asking for your favorite color. When I looked in the stored cookies and site data in Chrome settings, it said that the cookies had been stored for these other names, but they still did not return the values.
I am thinking the reason is that the "for" loop in function getCookie is not working. If x[0] (the name of the first cookie entered) has a value, great! The function returns the value of that cookie. However, if not, instead of looping back through the function (the loop), it just stops. (Again, this is just a guess.) I was thinking it had something to do with the fact that I had a "return" statement, which exits out of the loop, but it shouldn't act upon that statement unless the if condition is true (that said cookie name has a matching value--strangely, if and when it does return a value for these cookies that weren't the first ones created, it says, "Your favorite color is undefined.").
Any help?