There are many online calculators. You've probably seen, and perhaps used,
several. Some calculate mortgage payments, others calculate costs, and even more
calculate goofy things, like the number of days, hours, minutes, and seconds since you were born.
Here's a calculator that calculates ... well ... anything. It's a
Windows-like calculator that's similar to the one you have in your wallet
that lets you calculate how much money you have left in your checking account
after you write a check.
Here's a picture.
When you use this calculator with the ShowModalDialog method (explained in greater detail in my blog post
page in a new window of a specific size), you can return a calculated value
to the calling page. Here's how it works: you provide a link to the calculator
ShowModalDialog method; then when a user closes the calculator, the total is returned to
ShowModalDialog method. It's really much more simple than it sounds.
Here's some of the code
In the example
page, the "Calculate Numbers" link, code shown below, references a
The OpenCalculator function, shown in the following code, does a few
different things: it displays the calculator, returns a value from the
calculator, and places the returned value into a <span> tag.
var ret; var spanTag;
spanTag = document.all.tags
spanTag.innerText = ret;}
The calculator has several functions, too many to show here, and three global variables. The global
store the numbers and operators that the calculator needs to calculate the
values. The variable named total stores the current number that is being
calculated. When a user clicks the equals button, total resets to zero. The
variable named op stores the operator so that when the user clicks the plus
button, the calculator knows to add the numbers. The last variable, named isNew,
is a Boolean that indicates whether to reset the calculation to zero.
buttons call the SetNumber function, the operator buttons call the SetOperator
function, and the equals button calls the SetTotal function. Each of these
functions serves a very specific purpose, but the function that does all the
work is the Calculate function, shown in the following code. The Calculate
function takes the current operator (the operator button clicked last) and
calculates the last number entered (or the value in the number textbox) and places the
calculated value into the total variable.
var num = parseInt(document.Calculator.numbers.value);
total += num;
total -= num;
total *= num;
total /= num;
document.Calculator.numbers.value = total;
For an example of the calculator and the full code, see the example