PHP

Prefilling <form> data with JavaScript calculations

Another common use of JavaScript is to prefill a <form> with data from a calculation. Example 7-5 shows how data can be managed and updated in the winestore shopping cart (this approach isn't actually used in the online winestore).

When the user changes the quantity of wine he intends to purchase, an onChange event is generated. This change event is handled by the update( ) function, which modifies the value attribute of the total widget, showing the new total cost to the user. The new value shown to the user is calculated by multiplying together the quantity.value and the unit.value. Of course, as in all web database applications, the values and mathematics should be rechecked at the server when the <form> is submitted to the server.

Example 7-5. Using JavaScript to dynamically update values of <form> widgets
<!DOCTYPE HTML PUBLIC
              "-//W3C//DTD HTML 4.01 Transitional//EN"
              "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
   <title>Dynamic Form Update Example</title>
<script type="text/javascript">
<!-- Hide the script from old browsers
function update(quantity, unit, total)
{
    total.value = unit.value * quantity.value;
}
// end the hiding -->
</script>
</head>
<body>
<h1>Your Shopping Cart</h1>
<form method="get" action="test.php">
<table border="0" width="100%" cellpadding="0" cellspacing="5">
<tr>
  <td>Quantity </td>
  <td>Wine</td>
  <td>Unit Price</td>
  <td>Total</td>
</tr>
<tr>
  <td><input type="text" name="quantity" value="1"
       size=3 onChange="update(quantity,unit,total);">
  <td>1997 Anderson and Sons Wines Belcombe Grenache</td>
  <td>$<input type="text" value="17.29" name="unit"
        readonly></td>
  <td>$<input type="text" value="17.29" name="total"
        align="right" readonly></td>
</tr>
</table>
<input type="submit" value="Purchase Wines">
</form>
</body>
</html>