I'm putting together a very small project that requires the user to enter their age when they initially land on the homepage, via prompt. That age is then compared to a random number between 1 and 30; if their age is higher, they are directed to page A and if their age is lower, they are directed to page B.
I have the prompt and redirections set up, but what I'm now trying to do is set up an alert so that if the user does NOT fill in their age, they are forced to do so before moving on to one of the two pages (A or B, depending). At the moment, the alert shows up when either the "Cancel" or "OK" button is clicked during the initial prompt, but I cannot get the prompt to reappear after clicking "OK" on the alert.
My code is as follows:
Code:
$(window).load(function() {
var agePrompt=prompt("You should probably lie about your age:");
var randomnumber=Math.floor(Math.random()*31)
if (agePrompt==null || agePrompt=="") {
alert("You MUST lie about your age");
return false;
}
else {
if (agePrompt>=randomnumber) window.location.href="too-old.htm";
else {
window.location.href="take-a-seat.htm";
}
}
});
prompt() returns a string so you need to convert it to a number before comparing it to randomnumber:
Code:
agePrompt = parseInt(agePrompt);
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
Thanks for the help! I agree that the prompt() is not the best way to do it, so I set up a new version that should use text input to verify the age of the user. However, I'm not versed in script well enough to make it actually function.
<html>
<head>
</head>
<body>
<script type = "text/javascript">
function verify() {
var ageNum=parseInt(document.forms["age-verification"]["age"].value,10);// if you use parseInt() youmust specify the radix
var randomNumber=Math.floor(Math.random()*31);
if (isNaN(ageNum)) {
alert ("Please enter a numeric value for age");
document.forms["age-verification"]["age"].value = "";
return false;
}
if (ageNum>=randomNumber){window.location.href="too-old.htm"}
else { window.location.href="take-a-seat.htm"; }
}
</script>
<form name="age-verification" >
<label>Age</label>
<input name="age" type="text" size="3" maxlength="2">
<input name="b1" type="button" value = "Verify" onclick = "verify()">
</form>
</body>
</html>
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.