Forum Moderators: open
Most of it works, but I think the selection of coffee from the radio button is not being stored in the cookie, or at least I can not recall it. I was also wondering if there was some way that I could combine the makeCookie and welcome functions so that there would only be one button to click on the page.
Any ideas?
<html><head>
<title>Making a Cookie</title>
<script language="JavaScript">
function makeCookie(form){
var when = new Date();
when.setTime(when.getTime() + 24 * 60 * 60 * 1000);
// 24 hours from now
when.setFullYear(when.getFullYear() + 1);
// One year from now
yname=document.form1.yourname.value;
ycup=document.form1.coffee.value;
yroom=document.form1.yourroom.value;
document.cookie=escape("name")+"="+escape(yname, ycup, yroom)+
";expires="+when.toGMTString();
alert(document.cookie);
}
function welcome(){
you=document.form1.yourname.value;
room=document.form1.yourroom.value;
cup=document.form1.coffee.value;
var position=document.cookie.indexOf("name=");
if ( position!= -1){
var begin = position + 5;
var end=document.cookie.indexOf(";", begin);
if(end == -1){ end=document.cookie.length;}
you= unescape(document.cookie.substring(begin, end));
alert("Welcome " + you + ",\n\nwe will be sending a fresh cup of " + cup + "\n\nto you in room number " + room );
}
else{ alert("No cookies today");}
}
function seeDiscount(){
you=document.form1.yourname.value;
room=document.form1.yourroom.value;
cup=document.form1.coffee.value;
var position=document.cookie.indexOf("name=");
if(document.cookie == ""){
alert("No cookies totay");
return false;
}
else {
if ( position!= -1){
var begin = position + 5;
var end=document.cookie.indexOf(";", begin);
if(end == -1){ end=document.cookie.length;}
you= unescape(document.cookie.substring(begin, end));
alert("Welcome back " + you + ",\n\nGet a fresh cup of " + cup + " at 25% off today." );
}
else{ alert("No cookies today");}
}}
</script>
</head>
<body onLoad="seeDiscount()">
<h2>Room Service</h2>
<form name="form1">
What is your name? <br>
<input type="text" name="yourname" size="30">
<p>What is your room number? <br>
<input type="text" name="yourroom" size="3"> </p>
<p>What kind of coffee would you like?</p>
<p><input type="radio" name="coffee" value="Espresso">Espresso<br>
<input type="radio" name="coffee" value="Cappucino">Cappucino<br>
<input type="radio" name="coffee" value="Mocha">Mocha<br>
</p>
<p>
<input type="button" value="Make cookie" onclick="makeCookie();">
</p>
<p><input type="button" value="Welcome (Get cookie)" onclick="welcome();">
</p>
<p></p>
</form>
</body>
</html>
Radio buttons are an aray of values.
What you have to do is loop through the radio buttons and see which one is checked, and then get the value of that item.
e.g.
for (counter = 0; counter < document.form1.coffee.length; counter++)
{
if (document.form1.coffee[counter].checked) { // If this radio button item has been selected it will return true
ycup=document.form1.coffee[counter].value;
}
}