HTML Course 9.2 select, option and optgroup (dropdown lists)

HTML Course 9.2: select, option and optgroup (Dropdown Lists)

The <select> element creates a drop-down list in an HTML form. Its child elements are <option> (individual items) and <optgroup> (logical grouping of items). Below we explore each tag in depth, review common attributes, and provide illustrative examples.

1. The <select> Element

The <select> tag defines a control that allows users to select one or more options. It can be a simple single-choice dropdown, a multi-selection box, or even a list with visible items controlled by the size attribute.

Key Attributes of <select>

Attribute Description
name The name used when submitting form data; each selected option’s value is sent under this name.
multiple Allows selection of more than one option. When present, users can select several items via Ctrl/Cmd or Shift keys.
size Defines how many options are visible without opening the dropdown. If size > 1 and multiple is absent, it behaves like a single-selection list box.
disabled Disables the entire control, preventing user interaction and excluding it from form submission.
autofocus Gives focus to this control when the page loads (only one form control can have this).
required Makes selection mandatory before form submission.
form Associates the control with a <form> element by ID if the <select> is placed outside the form.

2. The <option> Element

Each <option> inside a <select> represents one choice. It may hold text content and optional attributes to control default selection or disable specific entries.

Key Attributes of <option>

Attribute Description
value The data value submitted if this option is selected. If omitted, the option’s text content is used.
label Provides an alternative shorter label for rendering; overrides the text content in some user agents.
selected Pre-selects this option when the page loads.
disabled Renders the option unselectable and visually disabled.

3. The <optgroup> Element

Use <optgroup> to logically group related <option> elements under a common label. Groups can also be disabled as a whole.

Attributes of <optgroup>

  • label: Required. The text to display as the group heading.
  • disabled: Optional. Disables all options within the group.

Examples

Example 1: Simple Single-Choice Dropdown



Example 2: Multi-Select List Box



Example 3: Grouped Options with <optgroup>



Example 4: Dynamically Enabling/Disabling Options



Best Practices

  • Always include a placeholder <option value=""> for required fields.
  • Use optgroup to improve usability when long lists need logical organization.
  • For accessibility, pair the <select> with a <label> and consider aria-describedby for help text.
  • Avoid overly long lists without search or filter functionality; consider custom widgets for very large datasets.


Posted

in

by

Tags:

Comments

Leave a Reply