HTML and CSS Reference
2.3. Calculating totals and displaying form output
In the previous section, you used data-* attributes to associate key/value pair data with
the quantity field, and you added <output> elements to the totals for each product and
for the order total. Yet, in its present state, the order form doesn't seem to care what values
you enter for the quantity fields—the total amounts are always $0.00.
In this section, you'll learn
• How to read input values in numeric format using the valueAsNumber property
• How to access data from HTML5 data-* attributes
• How to update the <output> element
In this section, you'll use the data-* attributes and <output> element to calculate the
totals and output the results to the user's browser. Four steps will get you there:
• Step 1: Add functions to calculate total values.
• Step 2: Retrieve the value of quantity input fields.
• Step 3: Retrieve price values and calculate line and form totals.
• Step 4: Display updated totals on the order form.
2.3.1. Building calculation functions
We'll start by building the functions that will perform the calculations in the order form
Step 1: Add functions to calculate total values
The code in listing 2.7 gets the relevant fields (quantity, item total, and order total) from
the DOM and sets up an event listener on each of the quantity fields to calculate the totals
whenever the user modifies the quantity value. The calculation code isn't shown in the list-
ing; you'll add that later in the chapter.
Open app.js and add the following code to the end of the init function, below the line
saveBtn.addEventListener('click', saveForm, false); .