JavaScript - Total an Order Form

A script that totals items using checkboxes and/or select lists.

Add up prices * number of orders per item to get the tally

Examples

Sample 1 - Table layout, checkbox and select, no decimal adjustment

Wonder Widget $10.50
Snow Widget $20.00

Total:


Sample 2 - Table layout, checkbox, no decimal adjustment

Wonder Widget $10
Snow Widget $20

Total:


Sample 3 - Table layout, select, decimal adjustment to 2 places

Wonder Widget $10.50
Snow Widget $20.99

Total:


Sample 4 - CSS layout, checkbox and select, no decimal adjustment, firstChoice = 2

Wonder Widget
$10
Snow Widget
$20
Total:

Sample 5 - Table layout, some only select, some only checkbox, no decimal adjustment

White Widget $10
Red Widget $11
Green Widget $12
Widgets w/ screws $20
Widgets w/ bolts $20

Total:

Setting up the script

  1. Download the OrderForm script: orderform04.js
  2. Include the script. Put the following between the <head></head> tags in your page.
    <script type="text/javascript" src="orderform04.js"></script>
  3. Set up to instantiate an OrderForm object when the page loads.
    <script type="text/javascript">
    //<![CDATA[
    window.onload = setupScripts;
    function setupScripts()
    {
    	var anOrder1 = new OrderForm();
    }
    //]]>
    </script>
  4. Make sure your html matches the naming conventions in the OrderForm script, or change the values in the script. You need unique ids for the form, text output, checkboxes, select lists, and the span tags that wrap the prices. Here is a simple xhtml example with the default name formats.
    <form id="frmOrder">
    <p>
    <input type="checkbox" id="chk0" />
    Wonder Widget
    $<span id="txtPrice0">10</span>
    <select id="sel0">
    	<option value="val0">0</option>
    	<option value="val1">1</option>
    	<option value="val2">2</option>
    	<option value="val3">3</option>
    </select>
    </p>
    <p>
    <input type="checkbox" id="chk1" />
    Snow Widget
    $<span id="txtPrice1">20</span>
    <select id="sel1">
    	<option value="val0">0</option>
    	<option value="val1">1</option>
    	<option value="val2">2</option>
    </select>
    </p>
    <p>
    <input type="text" id="txtTotal" size="8" />
    </p>
    </form>
  5. That's all you should need to get it working. Most changes to the html (such as removing the checkboxes) shouldn't require changes to the script. Refer to the Notes below for additional tips.

Notes

JavaScript Source

Public Domain

OrderForm v0.4 (found in the orderform04.js file) is released to the public domain. See Terms & Conditions for details. The content on this page is still copyrighted.

orderform04.js (5 KB)

About this page: