Categories
Web development

HTML Select, Option and Optgroup tags

HTML option tag

The HTML <select> tag creates a drop-down list.

The HTML <option> tag determines an option in a select list.

The HTML <option> tag goes inside a <select> tag.

Example:

<!DOCTYPE html>
<html>
<body>
    
<label for="webdev">Choose an option:</label>
<select id="webdev">
  <option value="option-1">HTML</option>
  <option value="option-2">CSS</option>
  <option value="option-3">JavaScript</option>
  <option value="option-4">jQuery</option>
</select>
  
</body>
</html>

Output:



The <select> tag can have the following attributes:

autofocus (value- autofocus) – the drop-down list gets focus when the page loads.

disabled (value- disabled) – the drop-down list is disabled.

form (value- form-id) – specifies to which form the drop-down list belongs.

multiple (value- multiple) – defines multiple options that can be selected at the same time.

name (value- name) – the name of the drop-down list.

required (value- required) – defines that the user is required to select a value before submitting the form.

size (value- number) – the number of options in a drop-down list.

The <option> tag can have the following attributes:

disabled (value- disabled) – the option is disabled.

label (value- text) – defines a short label for the option.

selected (value- selected) – the option is pre-selected when the page loads.

In case you have a lot of options, you can group related options with the <optgroup> tag:

<!DOCTYPE html>
<html>
<body>

  <label for="world">Choose an option:</label>
  <select name="world" id="world">
    <optgroup label="Europe">
      <option value="united-kingdom">United Kingdom</option>
      <option value="belgium">Belgium</option>
    </optgroup>
    <optgroup label="North America">
      <option value="usa">USA</option>
      <option value="canada">Canada</option>
    </optgroup>
  </select>
 
</body>
</html>

Output:






The <optgroup> tag can have the following attributes:

disabled (value- disabled) – the option-group is disabled.

label (value- text) – defines a label for the option-group.

Enjoy coding!