Click here to Skip to main content
15,919,121 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is the code, the function occurs when an img is clicked via the code below.
HTML
onclick="rollDice();"


The function calls upon the Element "rollResult" which then becomes the... well... result.

HTML
<h2 id="rollResult"></h2>


This is Paragraph that I would like to become the bearer of good or bad news.

HTML
<p2 id="winOrLose"></p2>


Below is the function executed upon clicking the img, it calls upon the rollResult element when defined as the variable "x" which I then go on to compare in an 'if' statement to the number 70. If result of the roll is greater than 70 you have won any other roll below 70 is a loss.

JavaScript
function rollDice() {
    var x = document.getElementById("rollResult");
    x.innerHTML = Math.floor((Math.random() * 100) + 1);
    
    if (x > 70) {
        resultFinal = "You've won.";
    } else {
        resultFinal = "You lose.";
    }
    document.getElementById("winOrLose").innerHTML = resultFinal;
    
}


However, when tested the button works fine issuing for a random number to be generated and one is displayed however the message of "You've won." or "You lose." is always "You lose." regardless of how many times I generate a number, something is wrong with my 'if' statement I think.

Can anyone help?
Posted

1 solution

You are setting x.innerHTML from the RNG, but then testing x in your if

Cheers,
Peter
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900