JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Exercises

Suggested solutions to these questions can be found in Appendix A.

Question 1

Q: 

 

Using the code from the temperature converter example we saw in Chapter 2, create a user interface for it and connect it to the existing code so that the user can enter a value in degrees Fahrenheit and convert it to centigrade.

A: 
<html>
<head>
<script language=JavaScript>
function convertToCentigrade(degFahren)
{
   var degCent;
   degCent = 5/9 * (degFahren - 32);
    
   return degCent;
}
    
function butToCent_onclick()
{
   var CalcBox = document.form1.txtCalcBox;
    
   if (isNaN(CalcBox.value) == true || CalcBox.value == "")
   {
      CalcBox.value = "Error Invalid Value";
   }
   else
   {
      CalcBox.value = convertToCentigrade(CalcBox.value);
   }
}
</script>
</head>
<body>
    
<form name=form1>
<P>
   <input type="text" name=txtCalcBox value="0.0">
</P>
   <input type="button"
         value="Convert to centigrade"
         name=butToCent
         onclick="butToCent_onclick()">
</form>
</body>
</html>

Save this as ch06_q1.htm.

The interface part is simply a form containing a text box into which users enter the Fahrenheit value and a button they click to convert that value to centigrade. The button has its onclick event handler set to call a function butToCent_onclick().

The first line of butToCent_onclick() declares a variable and sets it to reference the object representing the text box.

   var CalcBox = document.form1.txtCalcBox;

Why do this? Well, in our code when we want to use document.form1.txtCalcBox, we can now just use the much shorter CalcBox; it saves typing and keeps our code shorter and easier to read.

So

alert(document.form1.txtCalcBox.value);

is the same as

alert(CalcBox.value);

In the remaining part of the function we do a sanity check—if what the user has entered is a number (that is, it is not NotANumber) and the text box does contain a value, we use the Fahrenheit-to-centigrade conversion function we saw in Chapter 2 to do the conversion, the results of which are used to set the text box's value.

Question 2

Q: 

 

Create a user interface that allows the user to pick the computer system of her dreams, similar in principle to the e-commerce sites selling computers over the Internet. For example, she could be given a choice of processor type, speed, memory, hard drive size, and the option to add additional components like DVD-ROM drives, sound cards, and so on. As the user changes the selection, the price of the system should update automatically and notify the user of the cost of the system as she has specified it either by using an alert box or updating the contents of a text box.

A: 
<html>
<html>
<head>
    
<script language=JavaScript>
var CompItems = new Array();
CompItems[100] = 1000;
CompItems[101] = 1250;
CompItems[102] = 1500;
    
CompItems[200] = 35;
CompItems[201] = 65;
CompItems[202] = 95;
    
CompItems[300] = 50;
CompItems[301] = 75;
CompItems[302] = 100;
    
CompItems[400] = 10;
CompItems[401] = 15;
CompItems[402] = 25;
function updateOrderDetails()
{
   var total = 0;
   var orderDetails = "";
   var formElement;
   formElement =
      document.form1.cboProcessor[document.form1.cboProcessor.selectedIndex];
   total = parseFloat(CompItems[formElement.value]);
   orderDetails = "Processor : " + formElement.text;
   orderDetails = orderDetails + " $" + CompItems[formElement.value] + "\n";
    
   formElement =
      document.form1.cboHardDrive[document.form1.cboHardDrive.selectedIndex];
   total = total + parseFloat(CompItems[formElement.value]);
   orderDetails = orderDetails + "Hard Drive : " + formElement.text;
   orderDetails = orderDetails + " $" + CompItems[formElement.value] + "\n";
    
   formElement = document.form1.chkCDROM
   if (formElement.checked == true)
   {
      orderDetails = orderDetails + "CD-ROM : $" +
         CompItems[formElement.value] + "\n";
      total = total + parseFloat(CompItems[formElement.value]);
   }
    
   formElement = document.form1.chkDVD
   if (formElement.checked == true)
   {
      orderDetails = orderDetails + "DVD-ROM : $" +
         CompItems[formElement.value] + "\n";
      total = total + parseFloat(CompItems[formElement.value]);
   }
    
   formElement = document.form1.chkScanner
   if (formElement.checked == true)
   {
      orderDetails = orderDetails + "Scanner : $" +
         CompItems[formElement.value] + "\n";
      total = total + parseFloat(CompItems[formElement.value]);
   }
    
   formElement = document.form1.radCase
   if (formElement[0].checked == true)
   {
      orderDetails = orderDetails + "Desktop Case : $" +
         CompItems[formElement[0].value];
      total = total + parseFloat(CompItems[formElement[0].value]);
   }
   else if (formElement[1].checked == true)
   {
      orderDetails = orderDetails + "Mini Tower Case : $" +
         CompItems[formElement[1].value];
      total = total + parseFloat(CompItems[formElement[1].value]);
   }
   else
   {
      orderDetails = orderDetails + "Full Tower Case : $" +
         CompItems[formElement[2].value]
      total = total + parseFloat(CompItems[formElement[2].value]);
   }
    
   orderDetails = orderDetails + "\n\nTotal Order Cost is $" + total;
    
   document.form1.txtOrder.value = orderDetails;
}
    
</script>
</head>
    
<body>
<form name=form1>
<table>
<TR>
<TD width=300>
Processor
<br>
<select name=cboProcessor>
   <option value=100>MegaPro 1ghz</option>
   <option value=101>MegaPro 1.2</option>
   <option value=102>MegaPro 1.5ghz</option>
</select>
<br><br>
Hard drive
<br>
<select name=cboHardDrive>
   <option value=200>30gb</option>
   <option value=201>40gb</option>
   <option value=202>60gb</option>
</select>
<br><br>
CD-ROM
<input type="checkbox" name=chkCDROM value="300">
<br>
DVD-ROM
<input type="checkbox" name=chkDVD value="301">
<br>
Scanner
<input type="checkbox" name=chkScanner value="302">
<br><br>
Desktop Case
<input type="radio" name=radCase checked value="400">
<br>
Mini Tower
<input type="radio" name=radCase value="401">
<br>
Full Tower
<input type="radio" name=radCase value="402">
<P>
<input type="button" value="Update" name=butUpdate onclick="updateOrderDetails()">
</P>
</TD>
<TD>
<textarea rows=20 cols=35 id=txtOrder name=txtOrder>
</textarea>
</TD>
</TR>
</table>
</form>
</body>
</html>

Save this as ch06_q2.htm.

This is just one of many ways to tackle this question—you may well have thought of a better way.

I've decided to display the results of the user's selection as text in a textarea box, with each item and its cost displayed on separate lines with a final total at the end.

Each form element has a value that I've 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 defined at the beginning of the page. Why have I not just stored the price in the value attribute of each form element? Well, this way is more flexible. Currently our array just holds price details for each item, but we could modify that so it holds more data, for example price, description, number in stock, and so on. Also, if this form was posted to a server the values passed will be stock IDs, which we could then use for a lookup in a stock database. If the values were set to prices and the form was posted, we'd have no way of telling what the customer has ordered—all we'd know is how much it all cost.

I've chosen to have 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(), we can see there is a lot of code, and although it looks complex, it's actually fairly simple. A lot of it is repeated with slight modification.

To save on typing and make the code a little more readable, I've declared a variable, 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, we then find out which processor has been selected, calculate the cost, and add the details to the textarea.

formElement =
   document.form1.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 we set our formElement variable to reference that.

The same principle applies when we find the hard drive size selected, so let's turn next to the checkboxes for the optional extra items, looking first at the CD-ROM checkbox.

formElement = document.form1.chkCDROM
if (formElement.checked == true)
{
   orderDetails = orderDetails + "CD-ROM : $" +
      CompItems[formElement.value] + "\n";
   total = total + parseFloat(CompItems[formElement.value]);
}

Again, we set the formElement variable to now reference the chkCDROM checkbox object. Then if the checkbox is checked, we add a CD-ROM to the order details and update the running total. The same principle applies for the DVD and scanner checkboxes.

Finally, we have the case type. Because only one case type out of the options can be selected, we've used a radio button group. Unfortunately, there is no selectedIndex for radio buttons as there is for checkboxes, so we have to go through each radio button in turn and find out if it has been selected.

formElement = document.form1.radCase
if (formElement[0].checked == true)
{
   orderDetails = orderDetails + "Desktop Case : $" +
      CompItems[formElement[0].value];
   total = total + parseFloat(CompItems[formElement[0].value]);
}
   else if (formElement[1].checked == true)
{
   orderDetails = orderDetails + "Mini Tower Case : $" +
       CompItems[formElement[1].value];
   total = total + parseFloat(CompItems[formElement[1].value]);
}
else
{
   orderDetails = orderDetails + "Full Tower Case : $" +
      CompItems[formElement[2].value]
   total = total + parseFloat(CompItems[formElement[2].value]);
}

We check to see which radio button has been selected and add its details to the textarea and its price to the total. If our array of stock defined at the beginning of the code block had further details, such as description as well as price, we could have looped through the radio button array and added the details based on the CompItems array.

Finally, we set the textarea to the details of the system the user has selected.

orderDetails = orderDetails + "\n\nTotal Order Cost is " + total;
document.form1.txtOrder.value = orderDetails;

Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

Commercial Fridge Repairs Perth