How It Works - Page 15
September 28, 2001
Let's first look at the body of the page, where we define the
checkboxes, radio buttons and standard button inside a form
called form1. We start with the checkboxes. They are put into a
table simply for formatting purposes. No functions are called or
events are hooked into.
<TABLE>
<TR>
<TD>DVD-ROM</TD>
<TD><INPUT TYPE="checkbox" NAME=chkDVD VALUE="DVD-ROM"></TD>
</TR>
<TR>
<TD>CD-ROM</TD>
<TD><INPUT TYPE="checkbox" NAME=chkCD VALUE="CD-ROM"></TD>
</TR>
<TR>
<TD>Zip Drive</TD>
<TD><INPUT TYPE="checkbox" NAME=chkZip VALUE="ZIP Drive"></TD>
</TR>
</TABLE>
Next come the radio buttons for selecting the required CPU speed,
which are a little more complex. Again they are put into a table
for formatting purposes.
<TABLE>
<TR>
<TD><INPUT TYPE="radio" NAME=radCPUSpeed CHECKED
onclick="return radCPUSpeed_onclick(0)" VALUE="800 MHz"></TD>
<TD>800 MHz</TD>
<TD><INPUT TYPE="radio" NAME=radCPUSpeed
onclick="return radCPUSpeed_onclick(1)" VALUE="1 GHz"></TD>
<TD>1 GHz</TD>
<TD><INPUT TYPE="radio" NAME=radCPUSpeed
onclick="return radCPUSpeed_onclick(2)" VALUE="1.5 GHz"></TD>
<TD>1.5 GHz</TD>
</TR>
</TABLE>
The radio button group name is radCPUSpeed. I've set the first
one to be checked by default by including the word CHECKED inside
the <INPUT> tag's definition. It's a good idea to ensure
that you have one radio button checked by default. Without this,
if the user did not select a button, the form would be submitted
with no value for that radio group.
We're making use of the onclick event of each Radio object. For
each button we're connecting to the same function,
radCPUSpeed_onclick(), but for each radio button we are passing a
value, the index of that particular button in the radCPUSpeed
radio button group array. This makes it easy to work out which
radio button was selected. We'll look at this function a little
later, but first let's look at the standard button that completes
our form.
<INPUT TYPE="button" VALUE="Check Form" NAME=butCheck
onclick="return butCheck_onclick()">
This button is for the user to click when they have completed
filling in the form, and has its onclick event handler connected
to the butCheck_onclick() function.
So, we have two functions, radCPUSpeed_onclick() and
butCheck_onclick(). These are both defined in the script block in
the head of the page. Let's look at this script block now. It
starts by declaring a variable radCpuSpeedIndex. This will be
used to store the currently selected index of the radCPUSpeed
radio button group.
var radCpuSpeedIndex = 0;
Next we have the radCPUSpeed_onclick() function which is called
by the onclick event handler in each radio button. Our function
has one parameter, namely the index position in the radCPUSpeed[]
array of the radio object selected.
function radCPUSpeed_onclick(radIndex)
{
var returnValue = true;
Try It Out: Checkboxes and Radio Buttons - Page 14
Beginning JavaScript
How It Works (Con't) - Page 16
|