SoFunction
Updated on 2025-04-06

JavaScript Basic Tutorial (Continued by Lesson 5) Page 2/3

Menu is the most peculiar one of the form options we have learned. There are two basic formats: the following menu and the list menu. The following is an example:

Drop-down menu:
   

List menu:
   

The strange thing is that this menu has a name, but each of the options does not have a name. For example, in HTML, the first menu is as follows:

  <select name="pulldown_1" size="1">
    <option>probiscus </option>
    <option>spider </option>
    <option>lemur </option>
    <option>chimp </option>
    <option>gorilla </option>
    <option>orangutan </option>
  </select>

Note that the name of this menu is pulldown_1, but each option has no name. So it is a bit difficult to call each of the options.

Fortunately, the array can help us call the options in it. If you want to change the second option in the following menu, you can do this:

    .form_1.pulldown_1.options[1].text = 'new_text';

This is because the elements of the menu have an option attribute, which is an array of all options in the menu. Clickchange the selectt Then from the drop-down menu, see if its options have been changed from the following menu. Now the second option should be *thau*.

In addition to the option attribute, there is also an attribute called selectedIndex in the menu. After an option is selected, the selectedIndex property will become the array index number (serial number) of the selected array. Select an option in the 2nd list menu and checkIndex number. Remember that the index number of the 1st option in the array is 0.

    <a href="#" onClick="alert('index is: ' + .form_1.list_1.selectedIndex);return false;">check the index.</a>

The name of the form is form_1 and the name of the list menu is list_1. The selectedIndex property value is .form_1.list_1.selectedIndex. You're OK
Set selectedIndex as follows:

    .form_1.list_1.selectedIndex = 1;

And highlight the second option.

Once you get the index number of the option, you can find its content:

    var the_select = .form_1.list_1;

    var the_index = the_select.selectedIndex;

    var the_selected = the_select.options[the_index].text;

The selectedIndex property is useful, but what if multiple options are selected at the same time?

The processor of the menu element is onChange(). When the menu changes, the processor is activated.

Previous page123Next pageRead the full text