Live Update of Form Calculations
A client has a food delivery menu on their website. Customers specify how many of what items they want.
When they talked to me, site management needed a way to tell the person doing the ordering how many items they ordered and the total of the order — while they were ordering — before they got to the payment page.
Although theirs was a highly-customized implementation, a simplified version of the code is available for use by you.
Form fields for total number of items are updated as soon as the the person changes a number. Live. Instant. Total price can also be calculated and updated live.
The totals can be published in a form field, perhaps with a readonly
attribute so it can't be changed, or in a div
or span
tag so it's part of the surrounding text instead of in a form field.
Can you use it?
"Yes," if you have or wish to provide any of these or something similar for your site visitors:
-
A wish list (example below).
-
Calculate total time required for specific activities (example below).
-
An order form (example below).
-
Any list of items where people can specify how many of each item they want and, optionally, number of items multiplied by cost/area/time.
All total-updating functionalities for the examples are done with two JavaScript functions.
Three Examples
Here are three examples. The first is a wish list, the second is a time estimator, and the third is an order form. (The order form example is referred to in the Implementation Instructions.)
Example 1 — A Wish List
Use the form to indicate how many of each item you wish to have. The total items is automatically updated for you.
What Is Wished For | How Many |
---|---|
Trips around the world | |
Helpings of dessert | |
Books to read | |
TOTAL |
Example 2 — An Activities Total Time Required Calculator
The form is a calculator. Specify how many of each activity you wish to pursue and the total time required is automatically calculated.
How Often | Activity | Time |
---|---|---|
Play "tag" with the kids | 60 minutes | |
Leisurely country drive | 180 minutes | |
Drink of water | 5 minutes | |
Nap | 30 minutes | Total minutes required. |
Example 3 — An Order Form
This order form is something that might be used on a page containing product descriptions or on a one-page shopping cart.
This example will be referred to in the implementation instructions.
The order form presents two totals: (i) the total number of items and (ii) the total price. The totals are expressed in two different ways: (i) within a paragraph of text immediately below the order form and (ii) below that, within form text fields.
Order Form | ||
---|---|---|
How Many | Item | Price (USD) |
Red widget (with tassel tail) | $21.95 | |
Red widget (no tassel) | 18.95 | |
Widget holder | 14.95 | |
"How to Get Widgets at Wholesale" (paperback) | 8.95 | |
"The Lost Art of Trading Widgets" (hardcover) | 35.00 |
The total number of items is 0 and $0 is the total price.
Totals | |
---|---|
How Many | Price (USD) |
$ |
Implementation Instructions
The calculations and updating of the totals are done with two JavaScript functions. The functions are designed to be reused in other forms.
The implementation instructions refer to the third example, the order form.
Note: If you view the source code of this web page for the first two examples, you'll notice the function names are slightly different. For each function to operate on the same web page, the function names need to be unique.
An Overview of the Two Functions
JavaScript function AddListOfFieldValues() — The function does a simple adding up of form field values that the user has typed in.
You customize the function to tell it which form fields to add up, the number of decimal points the total shall have, and where to put the total.
JavaScript function TotalFieldValuesMultiplied() — The function multiplies the "how many" number the user has typed in with the associated price to get a subtotal. The subtotals are added together to arrive at a total price.
You customize the function to tell it which form fields to add up and which to multiply by, the number of decimal points the total shall have, and where to put the total.
The two functions have an outstanding operational difference: One adds the values of form fields. The other adds the results of multiplying the value in one form field with the value in another form field.
The Example Order Form HTML Source Code
Here is the source code of the HTML (non-JavaScript) section of the order form example. It's here for reference. You'll see it referred to when reading how to customize the two JavaScript functions.
<table border="1" cellpadding="7" cellspacing="0" style="border-collapse:collapse;"> <tr> <th colspan="3">Order Form</th> </tr> <tr> <th>How<br>Many</th><th>Item</th><th>Price<br>(USD)</th> </tr> <tr> <td> <input type="text" id="num1" onkeyup="AddListOfFieldValues(); TotalFieldValuesMultiplied()" onchange="AddListOfFieldValues(); TotalFieldValuesMultiplied()" style="width:2.5em;"> </td> <td> Red widget (with tassel tail) </td> <td style="text-align:right;"> <input type="hidden" id="price1" value="21.95"> $21.95 </td> </tr> <tr> <td> <input type="text" id="num2" onkeyup="AddListOfFieldValues(); TotalFieldValuesMultiplied()" onchange="AddListOfFieldValues(); TotalFieldValuesMultiplied()" style="width:2.5em;"> </td> <td> Red widget (no tassel) </td> <td style="text-align:right;"> <input type="hidden" id="price2" value="18.95"> 18.95 </td> </tr> <tr> <td> <input type="text" id="num3" onkeyup="AddListOfFieldValues(); TotalFieldValuesMultiplied()" onchange="AddListOfFieldValues(); TotalFieldValuesMultiplied()" style="width:2.5em;"> </td> <td> Widget holder </td> <td style="text-align:right;"> <input type="hidden" id="price3" value="14.95"> 14.95 </td> </tr> <tr> <td> <input type="text" id="num4" onkeyup="AddListOfFieldValues(); TotalFieldValuesMultiplied()" onchange="AddListOfFieldValues(); TotalFieldValuesMultiplied()" style="width:2.5em;"> </td> <td> "How to Get Widgets at Wholesale" (paperback) </td> <td style="text-align:right;"> <input type="hidden" id="price4" value="4.95"> 4.95 </td> </tr> <tr> <td> <input type="text" id="num5" onkeyup="AddListOfFieldValues(); TotalFieldValuesMultiplied()" onchange="AddListOfFieldValues(); TotalFieldValuesMultiplied()" style="width:2.5em;"> </td> <td> "The Lost Art of Trading Widgets" (hardcover) </td> <td style="text-align:right;"> <input type="hidden" id="price5" value="35.00"> 35.00 </td> </tr> </table> <p> The total number of items is <span id="numtag" style="font-weight:bold;">0</span> and <span style="font-weight:bold;">$<span id="pricetag">0</span></span> is the total price. </p> <table border="1" cellpadding="7" cellspacing="0" style="margin-top:.5em; border-collapse:collapse;"> <tr> <th colspan="2">Totals</th> </tr> <tr> <th>How<br>Many</th><th>Price (USD)</th> </tr> <tr> <td> <input type="text" id="numfield" readonly value="0" style="width:4em;"> </td> <td> <span style="vertical-align:-.015em;">$</span><input type="text" id="pricefield" readonly value="0" style="width:7em;"> </td> </tr> </table>
The form fields that are used for the calculations and are to be typed into have two attributes to cause JavaScript functions to do their calculations.
The attributes are onkeyup
and onchange
. Both call the two JavaScript functions and both are colored gold. (Only in the order form example are both functions called. In the other examples only one or the other function needs to be called. For your implementations, call only the functions that need to be called. See An Overview of the Two Functions for reference.)
The other color coding in the HTML source code is referred to in the paragraphs describing the customization of the two JavaScript functions.
The JavaScript Source Code
Here is the JavaScript source code for the order form example. Customization notes follow.
The JavaScript can go anywhere on your page or imported from an external file.
<script> /* Basic Form Field Addition and Multiplication Functions Version 1.0 August 29, 2016 See article at willmaster.com for instructions. Copyright 2016 Will Bontrager Software LLC https://www.willmaster.com/ This software is provided "AS IS," without any warranty of any kind, without even any implied warranty such as merchantability or fitness for a particular purpose. Use of this software is subject to the Website's Secret Software License Agreement. https://www.willmaster.com/software/WebSitesSecret/WS_LicenseAgreement.html */ function AddListOfFieldValues() {var DecimalPosition = 0; var FieldDestinationID = "numfield"; var OtherTagDestinationID = "numtag"; var AdditionListFieldIDs = new Array( "num1", "num2", "num3", "num4", "num5" );var total = new Number(0.0); for( var i=0; i<AdditionListFieldIDs.length; i++ ) { var v; if( ( v = document.getElementById(AdditionListFieldIDs[i]).value.replace(/[^\-\.\d]/g,"") ) ) { total += parseFloat(v); } } total = total.toFixed(DecimalPosition); if( FieldDestinationID.length ) { document.getElementById(FieldDestinationID).value = total; } if( OtherTagDestinationID.length ) { document.getElementById(OtherTagDestinationID).innerHTML = total; } } // function AddListOfFieldValues() function TotalFieldValuesMultiplied() {var DecimalPosition = 2; var FieldDestinationID = "pricefield"; var OtherTagDestinationID = "pricetag"; var AddAndMultiplyList = new Object(); AddAndMultiplyList["num1"] = "price1"; AddAndMultiplyList["num2"] = "price2"; AddAndMultiplyList["num3"] = "price3"; AddAndMultiplyList["num4"] = "price4"; AddAndMultiplyList["num5"] = "price5";var total = new Number(0.0); for( var numfield in AddAndMultiplyList ) { var v1, v2; if( ( v1 = document.getElementById(numfield).value.replace(/[^\-\.\d]/g,"") ) ) { if( ( v2 = document.getElementById(AddAndMultiplyList[numfield]).value.replace(/[^\-\.\d]/g,"") ) ) { total += parseFloat( parseFloat(v1) * parseFloat(v2) ); } } } total = total.toFixed(DecimalPosition); if( FieldDestinationID.length ) { document.getElementById(FieldDestinationID).value = total; } if( OtherTagDestinationID.length ) { document.getElementById(OtherTagDestinationID).innerHTML = total; } } // function TotalFieldValuesMultiplied() </script>
JavaScript Customization Notes
All text colors in these customization notes for the JavaScript source code are duplicated in the example order form HTML source code where applicable for easier correlation.
Customization for the two JavaScript functions is similar. But there are enough differences that each will be described separately.
Customization of the AddListOfFieldValues() function —
There are 4 places to customize. The customization area has a pale highlighted background.
-
var DecimalPosition = 0;
This specifies the number of decimal positions for the calculated result. The value 0 means only whole numbers. Any decimal position may be specified.
-
var FieldDestinationID = "numfield";
If you have a form field where the calculated result is to be inserted, specify the form field's ID value here. If the total is not to be inserted into a form field, specify a value of null (like FieldDestinationID = "";).
In the order form example, the form field where the calculated result is to be inserted is in the bottom form, under the "How Many" column.
-
var OtherTagDestinationID = "numtag";
If you have a
span
ordiv
tag where the calculated result is to be inserted, specify the tag's ID value here. If the total is not to be inserted into an HTML tag, specify a value of null (like OtherTagDestinationID = "";).In the order form example, the
span
tag where the calculated result is to be inserted is in the paragraph between the top order form and the bottom totals form. -
Because the line referenced here is longer than the width of this content column, it's put into a
pre
tag. Scroll as needed to view the entire line.var AdditionListFieldIDs = new Array( "num1", "num2", "num3", "num4", "num5" );
The id values between quotes are the id values of the order form fields where people type in how many they want of that item. You'll see the id values in the order form source code, also colored blue.
The list of id values you provide here are the fields the JavaScript function consults when it adds up the total items.
When those 4 customizations are done, the function is ready to use.
Customization of the TotalFieldValuesMultiplied() function —
There are 4 places to customize. The customization area has a pale highlighted background.
-
var DecimalPosition = 2;
This specifies the number of decimal positions for the calculated result. The value 2 means format the result with two decimal places, like currency. Any decimal position may be specified.
-
var FieldDestinationID = "pricefield";
If you have a form field where the calculated result is to be inserted, specify the form field's ID value here. If the total is not to be inserted into a form field, specify a value of null (like FieldDestinationID = "";).
In the order form example, the form field where the calculated result is to be inserted is in the bottom form, under the "Price (USD)" column.
-
var OtherTagDestinationID = "pricetag";
If you have a
span
ordiv
tag where the calculated result is to be inserted, specify the tag's ID value here. If the total is not to be inserted into an HTML tag, specify a value of null (like OtherTagDestinationID = "";).In the order form example, the
span
tag where the calculated result is to be inserted is in the paragraph between the top order form and the bottom totals form. -
var AddAndMultiplyList = new Object(); AddAndMultiplyList["num1"] = "price1"; AddAndMultiplyList["num2"] = "price2"; AddAndMultiplyList["num3"] = "price3"; AddAndMultiplyList["num4"] = "price4"; AddAndMultiplyList["num5"] = "price5";
The first line above, the one beginning with the
var
code, needs to be as it is. It initializes an array. The lines following the first line assign values to the array.In each line that assigns values to the array, the two quoted id values are the id values of corresponding form field id values in the order form:
-
The first quoted id value, the one between the square parentheses, is an id value of a text field in the order form where people type in how many they want of that item. You'll see the id values in the order form source code, also colored blue.
-
The second quoted id value, the one immediately before the semi-colon character at the end of the line, is an id value of a hidden field in the order form that specifies the price for the order form item. You'll see the id values in the order form source code, also colored blue.
Your implementation may have more or less than 5 lines for assigning values to the array.
The function takes the id values of each line and multiplies the values in their corresponding form fields. The result of each line's addition is added together to get the total price for the order.
-
When those 4 customizations are done, the function is ready to use.
Once the functions are ready, they can be pasted into the web page source code. As noted earlier, the JavaScript can be anywhere on the page or imported from an external file.
Testing
Testing consists of typing a number in each quantity field to verify the results are correct. Test once with each quantity field being the only one with a number in it. And test with several quantity fields having a number.
When that passes, your form or calculator, whatever you want to call it, is ready for use.
Depending on how you designed it, the total quantity, the total price, or both will automatically update as people use it.
(This article first appeared in Possibilities ezine.)
Will Bontrager