Chapter 29. Scripting Selection Boxes

The HTML specification provides the <select/> element so page authors can add a menu of options to a form. The menu the <select/> element generates can look like a drop-down list from which you can select only one item, or like a list box that allows you to select multiple items. These selection boxes have one or more <option/> elements inside the opening and closing <select> tags. The following HTML shows an example:

<select id="dayOfTheWeek" name="dayOfTheWeek" size="5">
    <option value="0">Sunday</option>
    <option value="1">Monday</option>
    <option value="2">Tuesday</option>
    <option value="3">Wednesday</option>
    <option value="4">Thursday</option>
    <option value="5" selected="selected">Friday</option>
    <option value="6">Saturday</option>
</select>

The number of options visible in the browser is determined by the <select/> element's size attribute, and it is this attribute that determines how the browser renders the <select/> element. If size is greater than 1, the browser renders the element as a list box showing the specified number of options at a time. If size is 1 or isn't specified, the browser renders the selection box as a drop-down list.

The <select/> element DOM object has a property called options, a collection of <option/> element objects. Every <option/> element inside the <select/> element is an item in the options collection. So, using the previous <select/> element, you can access the <option/> element for Monday, like this:

var dayOfWeek ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.