PDA

View Full Version : Help needed tweeking some cookie related javascript



dog
12-15-2006, 05:53 PM
I'm using javascript to check for a cookie before deciding whether or not to display a form.

At the moment I have the effect I'm looking for but the cookie is being written on completion of a prompt box rather than submission of a form:


<html>
<head>
<script type="text/javascript">
<!--


function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('return_user')
//if there is something other than nothing in the cookie, the form doesn't get shown
if (username!=null && username!="")
{
obj = document.getElementById('view1'); obj.style.display='none';
}
//else the form gets shown
else
{
obj = document.getElementById('view1'); obj.style.display='block';
//and a prompt comes up asking for a name
username=prompt('Please enter your name:',"")
if (username!=null && username!="")
{
setCookie('return_user',username,365)
}
else
{
obj = document.getElementById('view1'); obj.style.display='block';
}
}
}

//-->
</script>
</head>
<body onLoad="checkCookie()">

<div id="view1" style="display:none;">
<p>Content for first time users.... this will be in addition to the normal content.</p>
<form onsubmit="setCookie('return_user',username,365)">
<label for="name">Name: </label><input id="name">
<input type="submit" value="Enviar">
</form>
</div>

<div id="view2">Normal content.</div>


</body>
</html>

I'm trying to take the prompt box out and submit information for the cookie using the form instead. But I'm not very good with javascript.

Can anyone help?