In: Computer Science
In javascript, make a program that takes in a positive integer (entered on a textbox and submitted by clicking a button). Then, it displays the sum of all the integers between that number and zero.
<html><head><meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<script>
function add(n)
{
/*This function MUST USE RECURSION to do the sum of
the numbers.*/
}
function check()
{
/*This function takes the input entered and checks if
it's an integer. If it's not a number, it should say it's not. If
it is, it calls the other function, and after the sum is returned
by the other function, it is displayed.*/
}
</script>
</head>
<body>
<input type="text" name="numbers" id="numbers">
<input type="button" name="button" value="click"
onclick="add();">
<p id="result"> </p>
</body></html>
Hint: use isNaN() and parseInt() functions.
Solution)
Explanation:I have completed the code have also shown the output, please find the images attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function add(n) {
if (n < 1) return 0;
return n + add(n - 1);
}
function check() {
var x = parseInt(document.getElementById("numbers").value);
if (isNaN(x))
document.getElementById('result').innerHTML = "It's not a number";
else
document.getElementById('result').innerHTML = add(x);
}
</script>
</head>
<body>
<input type="text" name="numbers" id="numbers">
<input type="button" name="button" value="click" onclick="check();">
<p id="result"> </p>
</body>
</html>
Outputs: