I want to create a page that displays a message when the user gives input. But the moment I click on the button to display the message the page instantly reloads and clears out the page:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
</head>
<body>
<form onsubmit="return getFibonacci()">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
<script src="script.js"></script>
</body>
</html>
JavaScript Code:
function getFibonacci() {
try {
var num = document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
}
catch (err) {
document.getElementById("result").innerHTML = err;
}
}