Forms and Functions: Writing a Simple Calculator Program with JavaScript


Objective

The objective of this project is to learn how to write a simple calculator with the JavaScript programming language. You will learn how to write a simple JavaScript calculator that can add, subtract, multiply or divide two numbers. You will be able to run your program in a Web browser.

Introduction

This is an example of a first-time programming project. You will be writing a calculator that can add, subtract, multiply or divide two numbers. The project uses JavaScript, an interpreted programming language supported by most Web browsers. You will learn how to write an HTML file containing your program, and how to load and run the file in your browser.

In this project, you will learn the basics of how JavaScript functions can be written to work with HTML FORM elements. Specifically, you will be working with HTML INPUT elements, and using JavaScript's built-in parseValue() and basic math functions.

Preliminaries

Getting Started with JavaScript

Now that you've succeeded with writing an HTML file and opening it with your browser, you're ready to delve into JavaScript. The following link has a step-by-step tutorial that will give you a great introduction to JavaScript programming: http://www.webteacher.com/javascript/index.html

Writing a JavaScript Calculator

To help get you started, here is an example of a JavaScript calculator that adds two numbers. This is just one of many ways to accomplish this task. You can use this example as a basis for your program, or you can start from scratch. If you build from this example, you will need to add functions and buttons for subtraction, multiplication, and division.

Simple Adder

Enter a number:

Enter a number:

Answer =

Here is the JavaScript source code for the simple adder. After you have gone through the JavaScript tutorial (above), you should be able to read through this code and understand what it is doing. Note that the two methods for denoting JavaScript comments are different than the method for HTML comments:

<!-- 2005/11/08 Science Buddies: JavaScript calculator, adds two numbers -->
<HTML>
<HEAD>
<TITLE>Simple Adder</TITLE>

<!-- saved from url=(0030)http://www.sciencebuddies.org/ -->
<!-- When this code is saved as a local file, the preceding line tells Internet Explorer to treat this file according to the security rules for the Internet zone (plus any security rules specific for the Science Buddies website). -->
<SCRIPT LANGUAGE="JavaScript">
<!-- old browsers can't handle JavaScript functions so comment them out
// This is a single-line JavaScript comment.
// Below is a multi-line JavaScript comment.
/* CalculateSum: this function has 3 arguments:
   Atext, Btext and form. It converts Atext and Btext to
   numbers using the built-in JavaScript "parseFloat" method.
   It then uses the form argument to output the sum of the
   numbers to the form's Answer field. Notice that the
   function does *not* need to know the the names of the
   form's input fields. Those values are passed as arguments.
   It does need to know that the form has a field named
   "Answer" so that it can put the result there.

   Here is how to end a multi-line JavaScript comment: */

function CalculateSum(Atext, Btext, form)
{
var A = parseFloat(Atext);
var B = parseFloat(Btext);
form.Answer.value = A + B;
}

/* ClearForm: this function has 1 argument: form.
   It clears the input and answer fields on the form.
   It needs to know the names of the INPUT elements in order
   to do this. */

function ClearForm(form)
{
form.input_A.value = "";
form.input_B.value = "";
form.Answer.value = "";
}

// end of JavaScript functions -->
</SCRIPT>
</HEAD>

<BODY>

<P><FONT SIZE="+2">Simple Adder</FONT></P>

<FORM NAME="Calculator" METHOD="post">
<P>Enter a number: <INPUT TYPE=TEXT NAME="input_A" SIZE=10></P>
<P>Enter a number: <INPUT TYPE=TEXT NAME="input_B" SIZE=10></P>
<P><INPUT TYPE="button" VALUE="Add Numbers" name="AddButton" onClick="CalculateSum(this.form.input_A.value, this.form.input_B.value, this.form)"></P>
<P><INPUT TYPE="button" VALUE="Clear Fields" name="ClearButton" onClick="ClearForm(this.form)"></P>
<P>Answer = <INPUT TYPE=TEXT NAME="Answer" SIZE=12></P>
</FORM>

</BODY>
</HTML>

Terms, Concepts and Questions to Start Background Research

To write a simple program in JavaScript, you should do research that enables you to understand the following terms and concepts:

  • HTML concepts:
    • start tags and end tags,
    • comments,
    • the <HEAD> section,
    • the <SCRIPT> section,
    • the <BODY> section,
    • the <FORM> section,
    • the <INPUT> tag.
  • JavaScript concepts:
    • functions,
    • variables,
    • objects,
    • properties,
    • methods,
    • events.
  • specific JavaScript functions:
    • parseFloat()
  • general programming concepts:
    • reserved words,
    • control statements (e.g., if...else, loops).

Questions:

  • How do you use an HTML form to get input from the user and store it in a variable?
  • How do you program a button in an HTML form to call a JavaScript function?
  • How do you pass information from an HTML form to a JavaScript function using a variable?
  • How do you program a JavaScript function to display information in an HTML form?

Bibliography

Materials and Equipment

  • computer with Web browser (e.g., Internet Explorer, Firefox)
  • text editing program (e.g., Notepad)

Experimental Procedure

Using what you have learned about programming in Javascript, create a program that can add, subtract, multiply or divide two numbers supplied by the user.

Variations

  • Add error-checking to your program. For example, what happens if the user types in words instead of numbers? The JavaScript function isNaN() (for "is Not a Number") will be useful (you can look it up in the JavaScript reference). You will also need to use "if...else" statements to control the flow of the program (you can look up "if...else" statements in the JavaScript reference, and you can also study the next JavaScript programming project, on sorting a list of words: ABC's of Programming: Writing a Simple 'Alphabetizer' with JavaScript. Devise a way to test the input for validity before running calculations. If there is a problem, use the built-in JavaScript alert() method to display a message to the user, explaining the problem.

Credits

Ken Hess and Andrew Olson, Ph.D., Science Buddies


Last edit date: 2006-04-17 19:04:30

 

Science Buddies gratefully acknowledges its Presenting Sponsor


Science Fair Project Home      Our Sponsors      About Us      Volunteer      Donate      Contact Us      Online Store      Privacy Policy      Image Credits      Site Map

Science Fair Project Ideas      Science Fair Project Guide      Ask an Expert      Teacher Resources      Science Fair Competitions     


Copyright © 2002-2008 Kenneth Lafferty Hess Family Charitable Foundation. All rights reserved.
Reproduction of material from this website without written permission is strictly prohibited.
Use of this site constitutes acceptance of our Terms and Conditions of Fair Use.