Beginning JavaScript | 12

1234
[previous] [next]

Textareas, Checkboxes and Radio Buttons

Try It Out – Checkboxes and Radio Buttons

Let's look at an example that makes use of all the properties, methods, and events we have just talked about. The example is a simple form, which allows a user to build a computer system. Perhaps it could be used in an e-commerce situation for buying computers online with the exact specification determined by the customer.

<script language="JavaScript"> var radCpuSpeedIndex = 0; function radCPUSpeed_onclick(radIndex) { var returnValue = true; if (radIndex == 1) { returnValue = false; alert("Sorry that processor speed is currently unavailable"); document.form1.radCPUSpeed[radCpuSpeedIndex].checked = true; } else { radCpuSpeedIndex = radIndex; } return returnValue; } function butCheck_onclick() { var controlIndex; var element; var numberOfControls = document.form1.length; var compSpec = "Your chosen processor speed is "; compSpec = compSpec + document.form1.radCPUSpeed[radCpuSpeedIndex].value; compSpec = compSpec + "\nWith the following addtional components\n"; for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++) { element = document.form1[controlIndex]; if (element.type == "checkbox") { if (element.checked == true) { compSpec = compSpec + element.value + "\n"; } } } alert(compSpec); } </script>

Tick all of the components you want included on your computer

DVD-ROM
CD-ROM
Zip Drive

Select the processor speed you require

800 MHz 1 GHz 1.5 GHz

Save the page as ch6_examp6.htm and load it into your web browser. You should see a form like the one below:

6

Tick some of the checkboxes, change the processor speed and hit the Check Form button. A message box will appear giving details of which components and what processor speed you selected. For example, if you select a DVD-ROM and a Zip Drive, and 1.5GHz processor speed, you will see the following:

7

Note that the 1 GHz processor is out of stock, so if you choose that, a message box will appear telling you that it's out of stock, and the 1 GHz processor speed radio button won't be selected. The previous setting will be restored once the user dismisses the message box.

1234
[previous] [next]
and
Created: February 5, 2001
Revised: February 5, 2001

URL: http://webreference.com/programming/javascript/beginning/chap6/