1

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.

user1504591
  • 95
  • 2
  • 13
  • you should declare variables with "var" btw – Jon Wells Sep 20 '12 at 16:24
  • there's no reason to declare your code inside a form and there's definitly no need to submit this form. remove the form tag – Moataz Elmasry Sep 20 '12 at 16:25
  • 1
    Just as a note: You should only use `parseInt` if you are trying to keep just integer numbers. In that case, you really should get used to using the optional `radix` parameter. `var v=parseInt(document.forms[0].txt1st.value, 10);` If you want to allow floating point numbers, then the unary plus `+` is all you need. `var v = +document.forms[0].txt1st.value` – Jeremy J Starcher Sep 20 '12 at 16:40

1 Answers1

3

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.