skip to Main Content

Following is the code: I cannot find the mistake

<!DOCTYPE html>
<html>
<head>
  <title>Party Sequence</title>
</head>
<body>

<label for="inputN">Enter the value of n:</label>
<input type="number" id="inputN" min="1" step="1" value="1">
<button onclick="result2(number)">Calculate</button>
<p id="result"></p>

<script>
  number=document.getElementById("inputN").value;
    function result2(number)
    {
      return (number-1)**(number-2);
      document.getElementById("result").innerHTML="Result: "+ result2(number);
    }
</script>

</body>
</html>

I tried removing the (number) argument of function yet shows nothing on clicking the button.

3

Answers


  1. Test this

    <!DOCTYPE html>
    <html>
    <head>
      <title>Party Sequence</title>
    </head>
    <body>
    
    <label for="inputN">Enter the value of n:</label>
    <input type="number" id="inputN" min="1" step="1" value="1">
    
    <button onclick="calculateResult()">Calculate</button>
    
    <!-- Placeholder element to display the result -->
    <p id="result"></p>
    
    <script>
    // Function to calculate (number - 1)^(number - 2)
    function calculateResult() {
        // Read the value of 'n' from the input field
        var number = document.getElementById("inputN").value;
        // Calculate (number - 1)^(number - 2)
        var result = Math.pow((number - 1), (number - 2));
        // Insert the result into the HTML element with ID 'result'
        document.getElementById("result").innerHTML = "Result: " + result;
    }
    </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
  2. I’ve checked your code, it seems like you are trying to perform button click action using Javascript, and I noticed that you are trying to access "number" variable from Javascript on HTML. But we are unable to use javascript variables directly on HTML, So we can directly define the number on the javascript result2() function instead of passing arguments, and also you have to put the return on last.
    the code might look like,

    <!DOCTYPE html>
    <html>
    <head>
      <title>Party Sequence</title>
    </head>
    <body>
    
    <label for="inputN">Enter the value of n:</label>
    <input type="number" id="inputN" min="1" step="1" value="1">
    <button onclick="result2()">Calculate</button>
    <p id="result"></p>
    
    <script>
      function result2() {
        var number = document.getElementById("inputN").value;
        var result = (number - 1) ** (number - 2);
        document.getElementById("result").innerHTML = "Result: " + result;
        return result
      }
    </script>
    
    </body>
    </html>
    Login or Signup to reply.
  3. When you call return, the function exits and no code after return runs. Try adding return at the end of the function instead.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search