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
              "-//W3C//DTD HTML 4.01 Transitional//EN"
   <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 -->
<h1>Your Shopping Cart</h1>
<form method="get" action="test.php">
<table border="0" width="100%" cellpadding="0" cellspacing="5">
  <td>Quantity </td>
  <td>Unit Price</td>
  <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"
  <td>$<input type="text" value="17.29" name="total"
        align="right" readonly></td>
<input type="submit" value="Purchase Wines">

by BrainBellupdated