Sergi Sergi - 1 month ago 8
HTML Question

Correct syntax to display a recurrent function in an HTML document

I'm a bit lost as to why this code is not displaying anything, it used to work when I didn't have a wrapper function for the button and I entered the parameter for the factorialize function manually in the script, what am I doing wrong?

HTML

<div class="factorializing">

<h1> Factorialize a number </h1>

<input type ="text" id ="number"/>
<button id="factButton"> Factorialize</button>

<h1 id="factorialized"> </h1>

</div>


Javascript

document.getElementById("factButton").addEventListener("click", function(){

function factorialize() {
var input = document.getElementById("number").value;
var output = document.getElementById("factorialized");

if (input === 0) {
return output.innerHTML = 1;
}

else {
return output.innerHTML = input * factorialize(input - 1) ;
}
}
});

Answer

I think your looking for something like this:-

document.getElementById("factButton").addEventListener("click", function() {

  var input = document.getElementById("number").value;
   var output = document.getElementById("factorialized");
  
  function factorialize(input) {
    if (input === 0) {
      return 1;
    } else {
      return input * factorialize(input - 1);
    }
  }
  
  output.innerHTML = factorialize(input);
});
<div class="factorializing">

  <h1> Factorialize a number </h1>

  <input type="text" id="number" />
  <button id="factButton">Factorialize</button>

  <h1 id="factorialized"> </h1>

</div>

this will recursively call your factorialize function and set the output.

Comments