<option>

Draft

Definition

The <option> HTML element is used to define an individual option within a <select> or <datalist> element. It represents a selectable choice that users can pick from a list.

Here’s an example of how to use the <option> element within a <select> element:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="banana">Banana</option>
</select>

In this example, the <select> element contains three <option> elements. Each <option> element represents a choice: Apple, Orange, and Banana. The value attribute specifies the value that will be submitted when the form containing the <select> element is submitted. The text between the opening and closing <option> tags is the visible text that users will see in the dropdown list.

You can pre-select an option by adding the selected attribute to the desired <option> element:

<select>
  <option value="apple">Apple</option>
  <option value="orange" selected>Orange</option>
  <option value="banana">Banana</option>
</select>

In this updated example, the “Orange” option will be pre-selected when the <select> element is rendered, indicating that it is the default choice.

The <option> element can also be used within a <datalist> element to provide a list of suggestions for an <input> element:

<input list="fruits" />
<datalist id="fruits">
  <option value="Apple"></option>
  <option value="Orange"></option>
  <option value="Banana"></option>
</datalist>

In this example, the <datalist> element provides a list of options that will be suggested as the user types in the associated <input> element. The <option> elements within the <datalist> specify the available suggestions.

It’s worth noting that the <option> element can be further customized using attributes such as disabled to disable an option, label to provide a different label for the option, or selected to pre-select an option.

Related posts