56 Chapter 3—Intelligent Forms
To test the output element, we will program one of these little shopping carts for
three different products. The quantity of each of these products can be changed
via an input field. At the same time, the total number of items and the total price
are displayed under the shopping cart. Figure 3.11 shows a shopping basket with
five items.
Figure 3.11 Two “output” elements show the number of products and the price in total
The code for our example can be explained quickly and simply: To update the
output elements for each change in quantity, we use the form’s oninput event:
<form oninput="updateSum();">
<table>
<tr><th>Product<th>Price (US$)<th>Item number
<tr><td>Keyboard<td class=num id=i1Price>39.50<td>
<input name=i1 id=i1 type=number min=0 value=0 max=99>
<tr><td>Mouse<td class=num id=i2Price>26.30<td>
The output elements are defined after the table with the products and refer to the
IDs of the input fields via the for attribute:
<p>Your shopping cart contains <output name=sumProd for="i1 i2 i3"
id=sumProd></output> items. Total price:
<output name=sum for=”i1 i2 i3” id=sum></output> US$.
In the JavaScript code, a loop runs over all input elements, adding the quantities
and calculating the total price: