Multiple controls

This program shows how to change an HTML image using multiple form elements, and how to update those elements.

Programming Issues

This example combines the ideas from our previous examples. The form contains a text box, and:

The image can be changed using any of these four controls. The main difference from our previous examples is that in addition to obtaining values from the controls to determine how to change the image, this script also updates the controls that were not used to ensure they are consistent with the selection. This process is mainly intuitive. For the list box, for instance, rather than simply reading the selectedIndex attribute, we can assign a value to it. For instance, form.listSel.selectedIndex = 2; selects the third item in the list box (remember, the index begins at 0, so 2 is the third item after 0 and 1.

Another new concept is that we introduce a status variable, selected, to keep track of which image we are currently showing. Since we are using multiple controls, and we have to update them all, rather than accessing the attributes of each control whenever we need to find out what the current selection is, we just do this once and store the result in selected. Then, we just have to access the value in selected to find out what the current selection is. Note that by making sure that we change selected to match the selectedIndex of the list and drop boxes, we can just write form.listSel.selectedIndex = selected, for instance, to avoid having to find the value of selected and then updating selectedIndex once we know what it is. This also works the other way round - instead of writing if ( form.listSel.selectedIndex == 1 ) selected = 1; we can just write selected = form.listSel.selectedIndex;. This is another example of being efficient in writing code.

Because selected needs to be accessed by more than one function, we declare it outside of all the functions, giving it global scope. See our basic forms 2 example for a discussion of function scope and global scope.

Finally, we introduce a function, updateControls(), which is called by the other functions (rather than by the HTML code). The "change" functions (and we now have four, one for each of the controls, being changeImageList(), changeImageDrop(), changeImageRad() and changeImageButton()) just determine what the image should be changed to and update the value of selected, and then call the updateControls(), passing that selection as an argument. This means we can avoid duplicating the code in each of our three "change" functions. This is known as "code reuse".

One further addition is that as well as updating the image itself, we also update its alternate text using the alt attribute.

Demonstration

Welsh Flag




Source and Downloads