I went over more than a few 'too much recursion' questions and answers here but each of them solves a specific issue, yet I couldn't deduce a proper answer from them to answer this code error, how to solve it and why I'm getting that error:
<body>
<input type="number" id="num">
<input type="button" id="submit" onclick="factor()"><br>
<div id="yourResult"></div>
<script>
inputValue = document.getElementById('num').val;
function factor(n){
if(n==0){
return 1;
}
if(n==1){
return 1;
}
return n * factor(n-1);
}
function result() {
$('yourResult').append('<p>your factorial of ' + inputValue + ' equals to: ' + factor()+'</p>');
}
</script>
</body>
You need to pass the parameter value.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <input type="number" id="num"> <input type="button" id="submit" value="Get Factorial" onclick="result()"><br> <div id="yourResult"></div> <script> function factor(n){ if(n==0){ return 1; } if(n==1){ return 1; } return n * factor(n-1); } function result() { inputValue = document.getElementById('num').value; $('#yourResult').append('<p>your factorial of ' + inputValue + ' equals to: ' + factor(inputValue)+'</p>'); } </script> </body>
Hey @clusterBuddy make it correct document.getElementById('num').val
to document.getElementById('num').value
and try below code it will gives you the factorial result:
<script type="text/javascript">
function factor(){
var n=document.getElementById("num").value;
var factorial = function(n) {
if(n == 0) {
return 1
} else {
return n * factorial(n - 1);
}
}
document.getElementById("yourResult").innerHTML ="your factorial is"+factorial(n);
}
</script>
<body>
<input type="text" id="num">
<input type="button" id="submit" value="submit" onclick="factor()"><br>
<span id="yourResult"></span>
</body>
This function can be easier:
function factor(n) {return !!+n && (n <= 1 ? n : n * factor(--n))}
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.