View Full Version : Calculator

07-26-2009, 07:21 PM
Hello I wish to make a basic calculator in javascript for my fitness website.

There are three sections to the page, an input box, a submit button and a paragraph where i would like the result to come out.

I would like to take the figure inputed, and put it in this equation:
111.33 - (0.42 x Inputted Figure)
Then make it appear in the paragraph tag when the submit button is clicked.

I know very very basic javascript but I'm just trying to figure out where I should start, and how to structure it.
I would mucho appreciate any pointers :)

Philip M
07-26-2009, 08:31 PM
Here you are:-

<form name = "myform">
Enter a value <input type = "text" name = "nput1">
<input type = "button" name= "but1" value = "Calculate Result" onclick = "calc()">

Result <input type = "text" name = "result" readonly=readonly><br><br>
<p id = "rlt"></p>

<script type = "text/javascript">
function calc() {
var a = parseFloat(document.myform.nput1.value);
if (isNaN(a)) {
alert ("You must enter a numeric value!");
document.myform.nput1.value = "";
return false;
var res = (111.33 - (0.42 * a)).toFixed(2); // result to 2 decimal places
document.myform.result.value = res;
document.getElementById("rlt").innerHTML = "The result of the calcultion is " + res;

You may wish to improve the validation to check that the value entered is within a sensible range, min and max, and not negative. You give no details so this will be up to you. The result turns negative if an initial value > 265 is entered.

"This is the worst disaster in California since I was elected." - California Governor Pat Brown, discussing a local flood

07-26-2009, 08:38 PM
Brilliant, thanks :)