Introduction
In HTML, the <option>
element represents an option in a dropdown list (<select>
element) or a list of options in a <datalist>
element. It can be used within either of these elements to provide users with choices to select from.
Here’s the basic syntax of the <option>
element:
<!DOCTYPE html>
<html>
<head>
<title>Object Element Example</title>
</head>
<body>
<select>
<option value="value1">Option 1</option>
<option value="value2">Option 2</option>
<option value="value3">Option 3</option>
<!-- Additional options can be added here -->
</select>
</body>
</html>
Output :
In this example, each <option>
element represents a choice within the dropdown list. The value
attribute specifies the value that will be sent to the server when the form is submitted, while the content of the <option>
tag is the visible text that the user sees in the dropdown list.
You can also use the selected
attribute to preselect an option by default:
<select>
<option value="value1">Option 1</option>
<option value="value2" selected>Option 2 (Selected by default)</option>
<option value="value3">Option 3</option>
</select>
In a <datalist>
element, <option>
elements are used to provide a list of autocomplete options for an associated input field:
<input list="browsers">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
<option value="Opera">
</datalist>
Here, as the user types in the input field, they’ll be presented with autocomplete suggestions based on the options provided within the <datalist>
.
The <option>
element can also be used with JavaScript to dynamically manipulate dropdown options based on user interactions or data changes.