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
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
- jsfiddle/d2DqP/7 I tried in chrome, it just work fine. – xdazz Commented Jan 20, 2012 at 6:08
- for me it shows the table and then goes back to the form again in your jsfiddle too :(..i want it to stop on the table – tarashish Commented Jan 20, 2012 at 6:10
- Is the reload caused by a form submit event? – Jørgen Commented Jan 20, 2012 at 6:14
- but there is no submit event in the form – tarashish Commented Jan 20, 2012 at 6:21
- 1 @unussunu there is a input type button which on some browsers has the default action to submit. – khael Commented Jan 20, 2012 at 7:02
3 Answers
Reset to default 4Use <form onsubmit="return false;"> ... </form>
prevent the default action of the input button. You can do this by JQuery's preventDefault()
function .Or just <form onsubmit="return false;"> ... </form>
It's the problem of document.write
, have a look at what it means
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742345218a4426409.html
评论列表(0条)