Java Reference
In-Depth Information
Here you are displaying the results of the user's selection as text in a textarea box, with each item and
its cost displayed on separate lines and a fi nal total at the end.
Each form element has a value set to hold a stock ID number. For example, a full tower case is stock ID 402.
The actual cost of the item is held in arrays defi ned at the beginning of the page. Why not just store the
price in the value attribute of each form element? Well, this way is more fl exible. Currently your array just
holds price details for each item, but you could modify it that so it holds more data — for example price,
description, number in stock, and so on. Also, if this form is posted to a server the values passed will be
stock IDs, which you could then use for a lookup in a stock database. If the values were set to prices and the
form were posted, you'd have no way of telling what the customer ordered — all you'd know is how much
it all cost.
This solution includes an Update button which, when clicked, updates the order details in the textarea
box. However, you may want to add event handlers to each form element and update when anything
changes.
Turning to the function that actually displays the order summary, updateOrderDetails(), you can
see that there is a lot of code, and although it looks complex, it's actually fairly simple. A lot of it is
repeated with slight modifi cation.
To save on typing and make the code a little more readable, this solution declares two variables: theForm
to contain the Form object, and formElement, which will be set to each element on the form in turn and
used to extract the stock ID and, from that, the price. After the variable's declaration, you then fi nd out
which processor has been selected, calculate the cost, and add the details to the textarea.
formElement = theForm.cboProcessor[document.form1.cboProcessor.selectedIndex];
total = parseFloat(compItems[formElement.value]);
orderDetails = “Processor : “ + formElement.text;
orderDetails = orderDetails + “ $” + compItems[formElement.value] + “\n”;
The selectedIndex property tells us which Option object inside the select control has been selected
by the user, and you set the formElement variable to reference that.
The same principle applies when you fi nd the hard drive size selected, so let's turn next to the check
boxes for the optional extra items, looking fi rst at the CD-ROM check box.
formElement = theForm.chkCDROM
if (formElement.checked == true)
{
orderDetails = orderDetails + “CD-ROM : $” +
compItems[formElement.value] + “\n”;
total = total + parseFloat(compItems[formElement.value]);
}
Again, set the formElement variable to now reference the chkCDROM check box object. Then, if the
check box is checked, you add a CD-ROM to the order details and update the running total. The same
principle applies for the DVD and scanner check boxes.
Search WWH ::




Custom Search