Client Side Coding > Javascript & Ajax
Display message along with name stored in cookie
(1/1)
mdahlke:
I have a prompt box appear onLoad that asks for a persons name. I am trying to get the text in the page to say "Good Morning, 'username' ".
for the onLoad I want to use onLoad="checkCookie()" but it won't write the "message" with the name and will load a seperate page.
Basically what I am asking is how can I get the message + the name pulled from the cookie to display on the page?
var message = (depends on the time of day, Good Morning or Good Afternoon)
var username = (whatever the user puts in the prompt box)
--- Code: ---<script type="text/javascript">
var time=currentTime.getHours();
var message="Good Morning!";
if (time >= 12) {
message = "Good Afternoon!";
time = time - 12;
}
if (time == 0) {
time = 12;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
document.write("<h3 style='margin-top:45px;text-align:center'>" + message + " " + username + "</h3>");
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,365);
}
}
}
</script>
--- End code ---
mdahlke:
I did a lot of fiddling around and basically just need to figure out why there is an undefine at the end.
I stored the checkCookie() in an external file.
Is there a better way to do the document.write so that it isn't writing the function?
Inside the function I have it do a doc.write to so I am basically doing a doc.write(doc.write(checkCookie()))
I'm going to finish this but I solved it by writing out that last sentenced....
Original Code
--- Code: ---
<script type="text/javascript">
document.write (checkCookie())
</script>
--- End code ---
Fixed Code
--- Code: ---<script type="text/javascript">
checkCookie()
</script>
--- End code ---
Navigation
[0] Message Index
Go to full version