0

I need to create a simple form with a button that calculates a number into a factorial. The calculation has to be done from the button and the answer needs to pop up in an alert box.

Embarisngly I've tried to figure this out for hours but I can not get the button to work and the workaround is to hit enter but then the answer does not display.

<script>
var n = document.getElementById('x1').value;

function fac(N) {
  if (N > 1) return n * fac(N - 1);
  else return N;
}

alert("Answer is "+ fac(N));
</script>
<!DOCTYPE html>
<html lang="en-US">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>factorial</title>
</head>

<body>
  <h2>Generate Your Factorial!</h2>
  <form>
  <label>Enter Number: </label><br>
  <input type="text" id="x1"><br>
  <input type="button"  value= "Generate" onclick="fac(N)">
  </form>
</body>

</html>
kewlashu
  • 1,099
  • 10
  • 18
bmatthew
  • 1
  • 1
  • `onclick="fac(N)"` ... N is undefined – Jaromanda X Sep 15 '20 at 03:52
  • also, `var n = document.getElementById('x1').value;` this is run exactly once, on page load, when that element is empty - so you can't use `n` either – Jaromanda X Sep 15 '20 at 03:53
  • Are you certain about the tags you have selected for this question? I don't think this has anything to do with [tag:html-helper] or [tag:javahelp]... – Alexander Nied Sep 15 '20 at 03:57
  • Also JavaScript has nothing to do with Java, you may want to update your title. You call the function on a click, but the `alert()` sits outside the function and won't get called when you click the button. – Grismar Sep 15 '20 at 04:04

1 Answers1

0

I think there is a confusion between the value passed and the one used in the function, try something like this

    <!DOCTYPE html>
    <html lang="en-US">

    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>factorial</title>
    </head>

    <body>
    <h2>Generate Your Factorial!</h2>
    <form>
    <label>Enter Number: </label><br>
    <input type="text" id="x1"><br>
    <input type="button"  value= "Generate" onclick="getFac()">
    </form>
    <script>
    
    
    function fac(N) {
      if (N > 1) {
          return N * fac(N - 1)
          }
      else{
           return N
      }
    }
    
    function getFac(){
        var n = document.getElementById('x1').value;
        alert("Answer is "+ fac(n));
    }
    
    </script>
  </body>

  </html>
Sharath Mohan
  • 118
  • 1
  • 3