a Simple Javascript Calculator
|
This is a sample introduction to a web page, with a sample Javascript
to calculate P = D (X5 - 1)/(X - 1) + PE*E*X5 where X = (1+G)/(1+R):
When displayed by your browser it'll look like this:
To get this calculator, you stick the following stuff between <HEAD> and </HEAD>
<HTML>
<TITLE>Web Page Title goes here</TITLE>
<HEAD>
<SCRIPT LANGUAGE ="JavaScript">
<!--
function calc(inputs)
{
D = eval (document.inputs.D.value);
E = eval (document.inputs.E.value);
R = eval (document.inputs.R.value);
G = eval (document.inputs.G.value);
PE = eval (document.inputs.PE.value);
R = R/100;
G = 1 + G/100;
X = G/(1 + R);
P = D*(Math.pow(X,5) - 1)/(X - 1)+PE*E*Math.pow(X,5);
P = Math.round(100*P)/100;
document.inputs.Result.value=P}
//-->
</SCRIPT>
</HEAD>
|
This command (called calc)
expects to get a bunch of data (called inputs).
Somewhere in the BODY of the web page (where you want the calculator to appear), stick this:
<TABLE BORDER="1" BGCOLOR="#DDDDDD" CELLPADDING="2"><TD>
<FONT FACE="arial" SIZE="-1">
<FORM NAME="inputs">
Current Dividend = $<INPUT TYPE="number" NAME="D" SIZE=5 VALUE="0.72">
<BR>
Current EPS = $<INPUT TYPE="number" NAME="E" SIZE=5 VALUE="1.65">
<BR>
Discount Rate (as a percent) = <INPUT TYPE="number" NAME="R" SIZE=5 VALUE="8.0">%
<BR>
Earnings Growth Rate (as a percent) = <INPUT TYPE="number" NAME="G" SIZE=5 VALUE="7.0">%
<BR>
Estimated P/E Ratio (in 5 years) = <INPUT TYPE="number" NAME="PE" SIZE=5 VALUE="30">
<BR>
<FORM>
<INPUT TYPE="button" VALUE="Go !" SIZE = 5 ONCLICK= "calc(inputs); return true">
<I>Current Stock Price</I> = $
<INPUT TYPE="number" NAME="Result" SIZE=5> ... maybe :^)
</FORM>
</TD></TABLE>
|
... where you'll want to change the stuff in red and
and you can call it inputs (or anything else you like), and
the stuff that does all the work (between <HEAD> and </HEAD>) can be called calc (or anything else), and
the Result doesn't have to be called Result. You could call it SAM.
Note: The actual Javascript on this page (between <HEAD> and </HEAD>)
includes an "alert" message and a bunch of "comments" which start with //.
(That's for human consumption. Your browser will ignore them :^)
View the source to see how this is done.
For other examples, click here
(where you should View the source to see the Javascript).
Explanation (of sorts):
Between
<FORM NAME="inputs"> and </FORM>
is a ... uh ... FORM and it's called "inputs".
It collects data from the user with statements like
<INPUT TYPE="number" NAME="D" SIZE=5 VALUE="0.72">
This set of data is called "inputs" (because that's the name we gave to the FORM).
Then, at the end, it displays a button (with the word Go!) and, when it's clicked, it sends all this "inputs" data
to a JavaScript command called "calc", with the statement calc(inputs):
<INPUT TYPE="button" VALUE="Go !" SIZE = 5 ONCLICK= "calc(inputs); return true">
|