List boxes
This program shows how to change an HTML image with an HTML list box.
Programming Issues
This example uses the same three images as our basic forms 2 example.
Rather than using the onclick
event to call the function as we did in the previous two examples, we use
the onchange
property of the list box to call it. This event is triggered whenever the selection in
the list box is changed, which is exactly what we want.
In our basic forms 2 example, we called the function like this:
onclick="changeImage()"
. In this example, we call it like this:
onclick="changeImage(this.form)"
. That this.form
is a argument.
We also have to define the function differently: function changeImage(form) { }
. The form
here is
a parameter. The difference between an argument and a parameter is subtle. A parameter is a value that a function
expects to receive, whereas an argument is the value that is actually passed to a function. A function can therefore access
the arguments that are passed to it by referencing its parameters. In this case, the function uses its sole parameter to
determine precisely which <form>
in the HTML document contains the list box (the code this.form
refers to the <form>
that contains the control calling the function, i.e. "this" control in that
context.
By passing the argument in this way, we can refer to the list box as: form.listSel
, rather than
document.forms["basicForm"].listSel
, which is simpler. Note that, like other form controls, the
<select>
tag accepts the name
attribute, so we can refer to it directly in the JavaScript
code.
We use the selectedIndex
property of the list box to determine which element is selected. This index
is counted from 0
. Since we have three selections, we check in turn whether selectedIndex
is
0
, 1
or something else, which must be 2
in this case, since there are only three
elements in the list. We again change the src
property of the image to update it based on the
selectedIndex
.