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) ;
}
}
});
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.
document.getElementById("factButton").addEventListener("click", function() { var input = parseInt(document.getElementById("number").value, 10); document.getElementById("factorialized").innerHTML = factorialize(input); }); function factorialize(n) { return (n <= 0) ? 1 : n * factorialize(n - 1); }
<div class="factorializing"> <h1> Factorialize a number </h1> <input type="text" id="number" /> <button id="factButton">Factorialize</button> <h1 id="factorialized"> </h1> </div>
I would just write the value to the output each recursive call, while changing the value.
document.getElementById("factButton").addEventListener("click", function() { var input = document.getElementById("number").value; var output = document.getElementById("factorialized"); output.innerHTML = '' factorialize(Number(input)) function factorialize(input) { return output.innerHTML += '' + ((input === 0) ? 1 : (input * factorialize(input - 1))) } });
<div class="factorializing"> <h1> Factorialize a number </h1> <input type="text" id="number" /> <button id="factButton">Factorialize</button> <h1 id="factorialized"> </h1> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.