Reputation: 1965
I just wrote a small program which takes the input from user and shows the factorial table. Here is the code:
<h1>Table of factorials</h1>
<h3>Enter the number:<h3>
<form name="form1">
<input type="text" name="num" onchange="display(parseInt(document.form1.num.value))"/>
<input type="button" />
</form>
<script>
function factorial(n){
if(n<=1) return n;
else return n*factorial(n-1);
}
function display(x){
document.write("<table>");
document.write("<tr><th>n</th><th>n!</th></tr>");
for(var i =1;i<=x;i++){
document.write("<tr><td>"+i+"</td><td>"+factorial(i)+"</td></tr>");
}
document.write("</table>");
document.write("Generated at"+ new Date());
}
</script>
But the problem is the form reloads again immediately after showing the table.
But if i use the button to trigger the function by onclick="display(parseInt(document.form1.num.value))"
it does fine.
How to fix this?
EDIT: Just noticed that it works fine in firefox too. The problem is with chrome, opera and safari
Upvotes: 2
Views: 6128
Reputation: 36
prevent the default action of the input button. You can do this by JQuery's preventDefault()
function .Or just <form onsubmit="return false;"> ... </form>
Upvotes: 2