|
SelectsThere are two primary kinds of "selects", pulldown selects and list selects. Here are examples of each: The thing that makes select objects strange is that the whole select is named, but none of the select's options is.
Notice that the whole select is named pulldown1, but the individual options aren't named. This makes it difficult to access individual options. Luckily, through the magic of arrays and objects, there's a way to access and change the options of a select. If you wanted to change the second option of the pulldown menu, you'd type: document.form1.pulldown1.options[1].text = 'newText'; This works because the select element has an options property that is an array of all the select's options. You can grab one of the options in the array and change its text property. Try it - change the select and then scroll up to see that the pulldown menu actually changed. The second option in the pulldown select should now be *Frank*. In addition to the options property, selects have a property called selectedIndex. When one option in a select has been chosen, the selectedIndex property of the select will be the array number of the selected option. To test this, select one of the options in the list select (the second one) and then check the index. Remember that the first option in the array is option 0. The line I used to check this was: <A
HREF="javascript:void(null)" The form is named form1, the list select is named list1. To get the selectedIndex, I looked at window.document.form1.list1.selectedIndex. If you want, you can set the selectedIndex thus: document.form1.list1.selectedIndex = 1; and highlight the second option in the list1 select. Once you know the index number of the selected option, you can find out what it is: var theSelect = document.form1.list1; The selectedIndex property is great when you only have one option selected. What happens when you have more than one option selected? Well, that gets slightly stranger. If you want to know, here's some information about multiple selects. Just like the other form elements, the select element has a handler: onChange(). This handler gets called whenever there's a change to the select. Here is an example to show you how onChange works with a select. |