Radio buttons
This program shows how to change an HTML image with an HTML radio button group.
Programming Issues
In this example, we call changeImage()
whenever one of the three radio buttons is clicked,
triggering the onclick
event. We pass an argument (see previous example for
a discussion of function arguments) to the function that enables it to determine which of the three radio buttons was
clicked, so it can decide which image to change to.
If we look at the HTML source for this page, the onclick
event for the first radio button calls
changeImage(0)
; the onclick
event for the second radio button calls changeImage(1)
;
and the onclick
event for the third radio button calls changeImage(2)
. Thus, if the function
determines that n == 1
, for instance, it knows that it was the second radio button that was clicked.
Once the function determines which radio button was clicked by examining n
, it updates the image in the
same way as previous examples.
Note that our <input>
tags have both name
and id
attributes. Neither of these
are used by the script. However, each <input>
element in a group must have the name name
because
radio buttons are mutually exclusive; only one radio button of a group can be selected at any given time. Each element
in a group must have the same name
so that the browser can deselect the others in the group whenever one
element is selected. The id
attribute is used by the <label>
tag, which enables us to
select the radio buttons by clicking on their labels as well as the buttons themselves. The <label>
tag
associates a label with a button with reference to its id
, e.g.
<label for="wales">Wales</label>
associates the label "Wales" with the radio
button whose id
is "wales".
Also the first radio button contains the attribute checked="checked"
so that it is selected
automatically when the page is first loaded. In HTML this attribute can be simply specified as checked
, but
in XHTML attributes cannot be "empty", so we have give it a value. Any value will do, so
checked="pink fluffy dinosaur"
will work just as well as checked="checked"
.