Click here to Skip to main content
15,359,191 members
Please Sign up or sign in to vote.
1.11/5 (2 votes)
See more:
<!DOCTYPE html>
<html lang="en-us">

<head>
<meta charset="utf-8" />
<title>Roll to Hit!</title>
<meta name="description" content="Roll to Hit! - Version 0.5" />
<meta name="author" content="Carson Beck" />
<meta name="dcterms.rights" content="https://creativecommons.org/licenses/by-sa/4.0/" />
</head>

<!-- start of visible page -->
<body>

    <p id="prompt">Roll the to hit the evil Ogre!</p>
    <input type="button" value="Roll" onclick="RolltoHit();" />

    <!-- JavaScript code placed at end of <body> element -->
    <script>

    function RolltoHit() {
      var randomNumber = Math.floor((Math.random() * 20) + 1);

      if (randomNumber.value >= 10) {
        document.getElementById("prompt").innerHTML = randomNumber + " You hit!";
      } else if (randomNumber.value <= 9) {
        document.getElementById("prompt").innerHTML = randomNumber + " You miss the Ogre!";
      } else if (randomNumber.value == 20) {
        document.getElementById("prompt").innerHTML = "Natural 20! The beast is slain!";
      } else if (randomNumber.value == 1) {
        document.getElementById("prompt").innerHTML = "Natural 1! You dropped your sword!";
      }

    }

    </script>

</body>
</html>


What I have tried:

When I run the HTML it won't change the prompt at the top to the values I have defined. I'm not sure what's wrong, the console doesn't show any issues with the code.
Posted
Updated 12-Jul-21 12:15pm
Comments
Richard Deeming 13-Jul-21 5:32am
   
Your if tests make no sense:

* If the number is greater than or equal to 10, "You hit!" - OK;
* If the number is less than or equal to 9, "You miss the Ogre!" - OK;
* If the number is equal to 20, then it is also greater than 10 - this branch can never be reached;
* If the number is equal to 1, then it is also less than 9 - this branch can also never be reached;
Carson Beck 13-Jul-21 23:01pm
   
That's what I thought, so how should I go about setting that up?
Richard Deeming 14-Jul-21 3:35am
   
Move the unreachable branches before the others:
* If the number is equal to 1 ...;
* Else if the number is equal to 20 ...;
* Else if the number is greater than 10 ...;
* Else (if the number is less than or equal to 9 - this test is not required, since any other value is handled by the previous branch) ...;

1 solution

Remove the ".value" from the randomNumber checks. randomNumber is already the value.
   

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