html
  1. html-option-tag

HTML <option> Tag

  • The HTML <option> tag defines an option in a dropdown list in an HTML form.
  • It is used in conjunction with the <select> element and can have various attributes set to specify the value, label, and selected state.

Syntax

The basic syntax for the <option> tag is as follows:

<select>
  <option value="value1">Option 1</option>
  <option value="value2">Option 2</option>
  <option value="value3" selected>Option 3</option>
</select>

In this code example, we have created a dropdown list with three options. The value attribute specifies the value of the option, which is sent back to the server when the form is submitted. The text between the opening and closing tags is used to label the option. The selected attribute is used to pre-select an option when the page loads.

Example and Output

Here is an example of a dropdown list using the <option> tag:

<label for="cars">Choose a car:</label>
<select id="cars" name="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes" selected>Mercedes</option>
  <option value="audi">Audi</option>
</select>
Try Playground

The output of the above code looks like the following:

Explanation

The <option> tag is a child element of the <select> element, and its purpose is to define the options within the dropdown list. The value attribute specifies the value of the option, which is used to identify the option when the form is submitted. The text between the opening and closing tags is used as the label for the option. The selected attribute is used to pre-select an option when the dropdown list is rendered.

Use

The <option> tag is commonly used in HTML forms where users need to select one or more options from a list, such as selecting a country, a city, or a product category. It is also used in various web applications to provide a list of selectable items.

Important Points

  • The <option> tag can be used with the <select> tag to create a dropdown list.
  • The value attribute specifies the value of the option, which is sent to the server when the form is submitted.
  • The text between the opening and closing tags is used as the label for the option.
  • The selected attribute is used to pre-select an option when the dropdown list is rendered.
  • Multiple options can be selected by using the multiple attribute on the <select> tag.

Summary

The <option> tag in HTML is used to define a selectable option within a dropdown list. It is used in conjunction with the <select> tag and can have various attributes set to specify the value, label, and selected state. The <option> tag is used widely in HTML forms to provide users with selectable options.

Published on: