Javascript calculator result flashes

旧城冷巷雨未停 提交于 2019-12-20 05:36:09

问题


My Code: "edited, added "var" in front of all variable, thanks. I tried removing the <form> but it wouldn't function when I did.

<head>
<title>Calculator</title>
<script language="javascript">
function calculate()
{
var v=parseInt(document.forms[0].txt1st.value);
var w=parseInt(document.forms[0].txt2nd.value);
var x=parseInt(document.forms[0].txt3rd.value);
var y=703;
var z = (v/w/x*y).toFixed(3);
document.getElementById("display").innerHTML=z;
}

</script>
</head>
<body>
<form name="cal" method="post" action="">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input name="txt1st" type="text" id="txt1st"></td>
<td><input name="txt2nd" type="text" id="txt2nd"></td>
<td><input name="txt3rd" type="text" id="txt3rd"></td>
<td>x 703</td>
</tr>
</table>
<button onclick="calculate()">Calculate</button>
<div id="display"></div>
</body>

When I click the "Calculate" button the result displays in the div, but only for a split second then disappears. Keep in mind I'm very new to JavaScript. Any help appreciated, thanks.


回答1:


You are submitting the form and so the page is refreshing.

Add return false; to the end of your calculate function to prevent the form submission.



来源:https://stackoverflow.com/questions/12516783/javascript-calculator-result-flashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!