How to Calculate Order Form Totals in JavaScript

By Cathlene S. Baptista

Use JavaScript to keep track of values and provide totals on web pages.
i Thinkstock/Comstock/Getty Images

JavaScript is a scripting language used to add dynamic functionality to web pages. JavaScript is placed directly into a web page’s HTML and is used to add interactivity, such as user feedback and input validation, to otherwise static pages. JavaScript also interacts directly with items on a web page, such as input fields and buttons, so it can be used to update their attributes. JavaScript can be used, for example, to keep track of values entered by a user, add them and provide the total.

Calculating Order Form Totals in JavaScript

Step 1

Open a text editor and create a file with a .htm extension. This file will contain the markup (HTML) that defines the form and the form’s contents: two fields where the user enters numbers, a button to calculate a total based on the two numbers, and a total field that holds the total.

Step 2

Add three input fields to the form. Name the first input field “box1,” name the second input field “box2” and name the third input field “total.” Box1 will hold the first number, box2 the second number, and the total will be placed in the total field. Give the input fields a size of 3 and a maximum length of 3.

Step 3

Add an HTML button to the form. When clicked, the button passes the form and its elements (this.form) to a JavaScript function called runTotal(). Call the function using the onClick() event and give the button a name using the value= attribute.

Step 4

Add a JavaScript function (runTotal()) to the HTML section between JavaScript tags. This function receives the form elements, adds the values of box1 and box2 and places the result in the total input field. Use forward-slashes (//) to indicate comments.

Step 5

Declare two variables and assign them the values of box1 and box2. JavaScript uses the plus (+) sign to concatenate strings, so use the Number() function to ensure that JavaScript performs addition when adding the values.

Step 6

Add the two variable values and update the total field with the result.

Step 7

Open the .htm page in a browser. Type a number in box1, a number in box2, and click the button to add the numbers. The total will appear in the total field.