Calculator, JavaScript, WebApp

How To Create a Four Function Web Calculator using JavaScript


Overview

Browser_on_PCIt is assumed that the reader has some knowledge of HTML (HyperText Markup Language) and programming logic.  Access to reference materials (e.g. books, technical manuals, Internet) is a plus!

The four-function calculator page uses HTML, CSS and JQuery for web page presentation and JavaScript for program logic.  As the image to the left implies, all processing takes place on the client (personal PC).  No web server interactions.

This application executes on the web browser (e.g. Internet Explorer, Chrome) installed on your desktop or laptop computer.  After the HTML file loads into the browser, the code executes or waits on an event trigger to occur (e.g. click or load event).  The code is executed sequentially, top to bottom as JavaScript is an interpretive language.  Thus, any modification to the JavaScript code in the HTML file is effective immediately after a browser refresh.

The following sections exhibit and explain the code snippets for web page presentation and page processing including installation instructions.

The web calculator is hosted at this link:   JavaScript_Calculator


Web Page Presentation

<body>

<!-- Calculator FORM -->
<form name="CalculateIT">
<!-- Place border on FORM and border title accordingly -->
<fieldset style="border-color:green; background-color:beige">
<legend style="color:blue; font-size: 18pt; background-color:lightsteelblue"> <span id="myTitle"></span></legend>
<!-- Audit Trail and Intermediate Result textboxes -->
<table align="center">
<tr>
<td align="center">Audit Trail</td>
<td align="center">Intermediate Results</td>
</tr>
<tr>
<td><textarea id="t1" rows="15" name="AuditTape" cols="30"  readonly="readonly"></textarea></td>
<td><textarea id="t2" rows="15" name="AccumTape" cols="50" readonly="readonly"></textarea></td>
</tr>
</table>

<!-- Script to scroll both result windows to the bottom (keep most current entries visible) -->
<script type="text/javascript">
function Scroll_to_Bottom() 
	{
	document.getElementById('t1').scrollTop=document.getElementById('t1').scrollHeight;
	document.getElementById('t2').scrollTop=document.getElementById('t2').scrollHeight;
	}
</script>

<!-- Audit Trail and Intermediate Result textboxes -->
<br/> 
<table border="1" cellpadding="10" cellspacing="0" align="center" style="border-collapse: collapse ; background-color:DarkSeaGreen">
<tr>
<td>
<!-- Place border on keyboard and display components -->
<fieldset style="border-color:green; background-color:lightsteelblue">
<!-- Calculator Display Title -->
<span id="MaxInput"></span> Digit Display
<br/>
<!-- Calculator Display -->
	<input name="NumIn" size="15" value="" style="text-align:right; font-size: 10pt" readonly="readoly">
<!-- Calculator Error Message area -->
<br/>
<font color=red size="2"><span id="ErrMsg"></span></font>
<!-- Calculator Keypad -->
<br/>
      <input id="btnC"     type="button" value="C"   name="Fclear"  onClick="KeyPad(name, value)">&nbsp;
      <input id="btnCE"    type="button" value="CE"  name="Fcleare" onClick="KeyPad(name, value)">&nbsp;
      <input id="btnOFF"   type="button" value="off" name="Poff"    onClick="KeyPad(name, value)" style="background-color: red; ">&nbsp;
      <input id="btnON"    type="button" value="on"  name="Pon"     onClick="KeyPad(name, value)" style="background-color: green; color:lawngreen; ">&nbsp;
<br/>
      <input id="btn7"     type="button" value="7"   name="B7"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn8"     type="button" value="8"   name="B8"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn9"     type="button" value="9"   name="B9"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btnDIV"   type="button" value="/"   name="Fdiv"    onClick="KeyPad(name, value)">&nbsp;
<br/>
      <input id="btn4"     type="button" value="4"   name="B4"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn5"     type="button" value="5"   name="B5"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn6"     type="button" value="6"   name="B6"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btnMULT"  type="button" value="x"   name="Fmult"   onClick="KeyPad(name, value)">&nbsp;
<br/>
      <input id="btn1"     type="button" value="1"   name="B1"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn2"     type="button" value="2"   name="B2"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btn3"     type="button" value="3"   name="B3"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btnSUB"   type="button" value="-"   name="Fminus"  onClick="KeyPad(name, value)">&nbsp;
<br/>
      <input id="btn0"     type="button" value="0"   name="B0"      onClick="KeyPad(name, value)">&nbsp;
      <input id="btnDOT"   type="button" value="."   name="Bdot"    onClick="KeyPad(name, value)">&nbsp;
      <input id="btnEQUAL" type="button" value="="   name="Fequal"  onClick="KeyPad(name, value)">&nbsp;
      <input id="btnADD"   type="button" value="+"   name="Fplus"   onClick="KeyPad(name, value)">&nbsp;
</fieldset>
</td>
</tr>
</table>
</fieldset>
</form>
<u><i>myCalc</i></u> is for illustrative and educational purposes and does not represent a fully robust and tested calculator product<br>
Copyright &copy; 2015  Larry Belmontes, Jr.
</body>

The above snippet represents the HTML BODY section.  The FORM, which is within the BODY,  contains three control components (keypad, audit trail and results) used to interact with the web browser on your personal computer.  Below is a description of HTML used in this web page.

Line Description
4 FORM declaration.  It contains all interactive components contained within the <FORM> and </FORM> HTML tags.
6-7 Declare a green border with the title of myWeb Calculator.  The border surrounds all calculator components.  A beige background is applied within the green boarder.
9-18 Declare a one-row, two-column table containing two text boxes (AuditTape, AccumTape) centered horizontally within the FORM.
21-27 Javascript to scroll down both text boxes (AuditTape, AccumTape) simultaneously to keep current activity visiable.
31 Declares a one-row, one-column table to contain the display and keypad components centered horizontally within the FORM.  A DarkSeaGreen background is applied to the this table.
35 Declare a green border with a lightsteelblue background for keypad components (display, error message, keypad).
37 Display title (e.g. 12 Digit Display) on the calculator keypad.
42 Numeric entry text box on the calculator keypad.
43 Error message area to display errors in red.
44-69 The buttons representing the calculator keypad.  Each button has unique IDs, names and values.  Additionally, each button utilizes the onClick event to invoke function “KeyPad(name, value)” where name is name of the button and value is the value on the button.  The onClick event is similar to posting a page to a web server.

Application Processing Logic

<script language="JavaScript">
//'
//'********************************************************
//' My first web calculator using JavaScript (client-side)
//'
//' Author     : Elario Belmontes, Jr.
//' Description: Four function calculator simulator for
//'              educational purposes to illustrate the 
//'              use of a web page on a personal web
//'              server
//' Languanges : JAVASCRIPT, JQUERY, HTML, CSS
//' File Name  : calc_42j.html
//' Disclaimer: This software is intended for educational learning
//'             purposes.
//'
//'             This software is provided "AS IS" and without any
//'             expressed or implied warranties, including, without
//'             limitation, the implied warranties of merchantability
//'             and fitness for a particular purpose.
//'
//'             No guarantee; No warranty; Install / Use at your own risk.
//'
//'
//' This version will execute the the script top to bottom
//' initially.  Subsequent executions are via onClick events
//' are facilitated via functions in the script. Additionally,
//' all variables maintain current state between events.
//'
//' Copyright (C) 2015  Larry Belmontes, Jr. 
//'
//'********************************************************
//'
//'
//'********************************************************
//' Declare variables
//'********************************************************
var firstPass = true;
var frm_AuditTape = "";
var frm_NumIn = "";
var frm_AccumTape = "";
var ErrMsg = "&nbsp;";
var MaxInput = 12;
var NumberIn = "";
var NumberInFunction = "";
var myTitle = "Welcome to myCalculator and happy calculating!";
var url = window.location.pathname;
var myScriptName = url.substring(url.lastIndexOf('/')+1);
//alert(myScriptName);

//'
//'********************************************************
//' Function: window.onload
//' Execute function when document is finished loading
//'********************************************************
window.onload = function()
{
	//alert("window.onload");
    document.getElementById("myTitle").innerHTML = myTitle;
    document.getElementById("ErrMsg").innerHTML = ErrMsg;
    document.getElementById("MaxInput").innerHTML = MaxInput;
}

//'
//'********************************************************
//' Function: KeyPad
//' Process button pressed
//'********************************************************
function KeyPad(Key_Name, Key_Pressed)
{
	switch (Key_Name)
	{
		//'
		//'********************************************************
		//' Math functions: add, subtract, multiply, divide
		//'********************************************************
		case document.getElementById("btnADD").name:
		case document.getElementById("btnSUB").name:
		case document.getElementById("btnMULT").name:
		case document.getElementById("btnDIV").name:
	   		Do_Math(Key_Pressed);
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Terminate Math function: equals
		//'********************************************************
		case document.getElementById("btnEQUAL").name:
	   		Finalize_Math(Key_Pressed);
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Housekeep: Clear all
		//'********************************************************
		case document.getElementById("btnC").name:
	   		Clear_key();
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Housekeep: Power Off
		//'********************************************************
		case document.getElementById("btnOFF").name:
	   		Power_Off_key();
			break;
		//'			
		//'********************************************************
		//' Housekeep: Power On
		//'********************************************************
		case document.getElementById("btnON").name:
	   		Power_On_key();
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Housekeep: Clear Entry
		//'********************************************************
		case document.getElementById("btnCE").name:
	   		Clear_Entry_key();
			Update_Page();
			break;			
		//'
		//'********************************************************
		//' Numeric entry
		//'  Limit to 16 digits entry excluding decimal point
		//'********************************************************
		case document.getElementById("btn0").name:
		case document.getElementById("btn1").name:
		case document.getElementById("btn2").name:
		case document.getElementById("btn3").name:
		case document.getElementById("btn4").name:
		case document.getElementById("btn5").name:
		case document.getElementById("btn6").name:
		case document.getElementById("btn7").name:
		case document.getElementById("btn8").name:
		case document.getElementById("btn9").name:
   			Numeric_Key(Key_Pressed);
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Decimal point entry
		//'********************************************************
		case document.getElementById("btnDOT").name:
	   		Decimal_key();
			Update_Page();
			break;
		//'
		//'********************************************************
		//' Invalid button detected
		//'********************************************************
			default:
			alert("Invalid button detected" + "\r\n" + "Name=" + Key_Name + "  Value=" + Key_Pressed);
			ErrMsg = "ERROR: Invalid button detected...";
			Update_Page();
			break;
	}
}

On the initial calculator submission, the code starts execution at line 1 executing declaration of variables logic and function windows.onload.  The remaining functions are not executed.  The FORM HTML is executed rendering an initialized calculator page.

On subsequent calculator submissions, the button onclick event triggers function KeyPad.  KeyPad processes the appropriate button logic including updating of textboxes and messages.  The detection of a specific button uses the getElementById method to obtain the button name for use in the case statements.  The browser renders updated content on the calculator page.

Below is a description of the JavaScript logic for the above snippet.

Line Description
38-48 Declare variables.
56-61 window.onload function executed when document completes loading on browser
 68 Function KeyPad always receives control from a button onclick trigger and acts as a function dispatcher
76-82 When buttons  +      x  or   /   are detected, call function Do_Math
 87-90 When button  =  is detected, call function Finalize_Math
 95-98 When button  C  is detected, call function Clear_key
 103-105 When button  off  is detected, call function Power_Off_key
 110-113 When button  on  is detected, call function Power_On_key
 118-121 When button   CE  is detected, call function Clear_Entry_key
 127-139 When buttons  0   1   2  3   4   5  6   7   8  or   9   are detected, call function Numeric_key
 144-147 When button  .  is detected, call function Decimal_key
 153-156 Catch-all code for invalid calculator key detection
 158 End of Function KeyPad

Download and Install JavaScript Web Calculator

This application was successfully tested using IE, Chrome, Firefox and Opera browsers as of this post.

1. Download the ZIP file and extract to a temporary directory.

Download calc_42j_html

2. Open the ZIP file and copy file, calc_42j.html, to the desktop.

3. On your desktop, double-click the calc_42j.html icon.

4. The calculator web page should display

5. On the calulator keyboard, click the following button in sequence –
3   +   7   /   2   =    The result should be 5

6. Happy calculating!!


Next Learning Experience

Extend the calculator exercise into the .NET space using ASPX (Active Server Page Extended).  ASPX will be very similar to the ASP calculator VBScript logic.

Take a look at related posts below!

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image

This site uses Akismet to reduce spam. Learn how your comment data is processed.