skip to Main Content

Here, everything is working just fine. I only need my button tag to call the function which displays a random number on the p tag in DOM and not me refreshing the page all the time.[Here is my HTML]And here is my script(https://phpout.com/wp-content/uploads/2023/05/qtODL-jpg.webp)

I tried using the click

Also tried the inline method on my HTML but it’s ignoring the call.

2

Answers


  1. Make a function in your script

    function makerandom() {
    document.getElementById("compscr").innerHTML = Math.floor(Math.random() * 5) + 1;
    }
    

    Also, add onclick="makerandom()" into your button in HTML
    And add your script to tour html using the <script> tag

    Login or Signup to reply.
  2. You have a couple of tings you are missing before your code works. If I have to answer your question how do you get your button to call a function, then you need to go through some steps.

    1. have the script/js code linked to your html first. I have added a script tag in the end of the body.
    2. Add a listener to the button tag. eg. <button id="click" onclick="randnum()">Play</button>
    <head>
      <title>Guess right</title>
    </head>
    
    <body>
      <div>
        <input id="userInput" type="number" />
        <p id="compscr"></p>
        <button id="click" onclick="randnum()">Play</button>
      </div>
    
      <script>
        let compscr = document.getElementById("compscr")
        let userInput = document.getElementById("userInput")
        let click = document.getElementById("click")
    
        const randnum = () => {
          document.getElementById("compscr").innerHTML = Math.floor(Math.random() * 5) + 1;
        }
    
        window.onload = function() {
          randnum();
        }
      </script>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search