0

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

0

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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!

Comments

0

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;
}

DEMO

Comments

0

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);

Comments

0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.