Reputation: 269
I've got a webpage which is meant to generate a random number, then when the number =5 it displays a win message..if not display lose message, but its not displaying any alerts..have i missed something out?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
return x;
if (x=4)
{
alert("winner!");
}
else
{
alert("loser");
}
}
</script>
</head>
<body>
<p id="demo">Click the button to display a random number between 1 and5.</p>
<button onclick="WinLose()">Try it</button>
</body>
</html>
EDIT: Managed to get this bit working so now it displays either win or loose depending on its number, yet does anyone know how i can swap the alerts in the if statements to display a DIV section. ive got a jQuery file included so it can accept the hide/show effect...anything i tried didnt work
Upvotes: 0
Views: 630
Reputation: 7802
Here is a simplified version that externalizes the alerts (I assume you don't plan to use them later)
function WinLose(){
var x=Math.floor((Math.random()*5)+1);
document.getElementById("demo").innerHTML=x;
return (x==5) ? "Winner!" : "Loser";
}
alert(WinLose());
Upvotes: 0
Reputation: 71
Your code:
x=x.innerHTML=Math.floor((Math.random()*5)+1);
x
is receiving x.innerHTML
then x.innerHTML = random number
.
Correct way: (remove "x=")
x.innerHTML = Math.floor((Math.random()*5)+1);
Upvotes: 0
Reputation: 5353
You need to return x
after you generate the random value; and you must add x == 4
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
if (x==4) {
alert("winner!");
} else {
alert("loser");
}
return x;
}
Upvotes: 0
Reputation: 62
Yeah, It can be tough. The main problem again has to be other than return x
is the "==". So this
if (x=4)
Should really say:
if (x==4)
What you said before was that you were assinging x to 4 so that has no meaning at all and messes everything up.
Hope this helps you!
Upvotes: 2
Reputation: 14565
you have return x
after you generate a random value for x. this means no javascript code after that line will run in that function.
also, your if statement needs to use '==' to do the comparison rather than '=' which is assignment.
Upvotes: 3