The select element and its associated options provide a way to choose one or more items from a list. It’s defined using the following syntax:

<select name="theSelection" multiple>
<option value="Opt1">Option 1</option>
<option value="Opt2">Option 2</option>
<option value="Optn">Option n</option>

The select element has the following properties that are accessible from JavaScript:


Whether the element is disabled


The containing form


Number of options in options array


Array of options


For single select, number of item selected; for multiple, first item selected


Type of element

The select options are included in the options array. Each of these are objects, themselves with several properties. However, for forms validation, the properties of interest are selected, value, and text. The selected property is set to true if the option is selected; the option value is given in value, and the text that’s visible to the web-page reader is given in text.

There are two ways to get the selected options from a selection, depending on whether multiple options can be selected or only one. If only one option can be selected at a time, using the select property of selectedIndex on the options array returns the selected object:

var slIdx= document.formname.theSelection.selectedIndex;
var opt = document.formname.theSelection.options[slIdx];

If multiple options can be selected, the code needs to iterate through the entire options array ...

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.