Reputation: 49
I'm a bit confused on calling the function correctly in this HTML doc. What am I doing wrong? The function should return the sum of all numbers between 1 and whatever number entered on the input field but is returning NaN instead. How do I assign and display the returned value from the function to the disabled input field?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Recursion</title>
<script>
let recursiveSum = (num) => {
if (num === 1) {
return 1;
} else {
return num + recursiveSum(num-1);
}
}
</script>
</head>
<body>
<h1>Find the sum of 1 to some number!</h1>
<form id="myForm" name="myForm">
<input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus>
<input type="text" id="sum" name="sum" disabled>
<button type="button" onclick="recursiveSum(this.form.numInput.value);">Calculate! </button>
</form>
</body>
</html>
Upvotes: 0
Views: 84
Reputation: 36584
Currently your function doesn't explicitly return any value so undefined
is returned from function implicitly.
Also setting value
in each recursive call doesn't make any sense. You should set the value after the result of all the recursion.
const elm = document.getElementById("sum")
function btnClick(num){
let recursiveSum = (num) => {
if(num === 1) return 1;
return num+recursiveSum(num-1)
}
elm.value = recursiveSum(+num)
}
<h1>Find the sum of 1 to some number!</h1>
<form id="myForm" name="myForm">
<input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus>
<input type="text" id="sum" name="sum" disabled>
<button type="button" onclick="btnClick(this.form.numInput.value);">Calculate! </button>
</form>
Upvotes: 1
Reputation: 5348
You need to separate the computation from showing the value, so you can properly compute the sum. Once you got the sum, displaying it is easy.
let recursiveSum = (num) => {
if (num === 1) {
return 1;
} else {
return num + recursiveSum(num - 1);
}
}
let showSum = (num) => {
document.getElementById("sum").value = recursiveSum(num);
}
<h1>Find the sum of 1 to some number!</h1>
<form id="myForm" name="myForm">
<input type="number" id="numInput" name="numInput" placeholder="Enter a positive number here" autofocus>
<input type="text" id="sum" name="sum" disabled>
<button type="button" onclick="showSum(parseInt(this.form.numInput.value));">Calculate! </button>
</form>
Upvotes: 1