Adding Structure to a select Element

Description

You can add some structure to a select element by using the optgroup element.

It has local attributes:label, disabled and contains option elements.

You use the optgroup element to group option elements together.

The label attribute lets you create a title for the grouped options.

The disabled attribute makes the option elements not selectable.

Example

The following code shows the optgroup element in use.


<!DOCTYPE HTML>
<html>
<body>
  <form method="post" action="http://example.com/form">
    <p>
      <label for="fave" style="vertical-align: top"> Favorite
        Fruit: <select id="fave" name="fave">
          <optgroup label="Top  Choices">
            <option value="apples" label="Apples">Apples</option>
            <option value="oranges" label="Oranges">Oranges</option>
          </optgroup>
          <optgroup label="Others">
            <option value="cherries" label="Cherries">Cherries</option>
            <option value="pears" label="Pears">Pears</option>
          </optgroup>
      </select>
      </label>
    </p><!--from www  .j a v  a  2 s .c  om-->
    <input type="submit" value="Submit" />
  </form>
</body>
</html>

Click to view the demo

The optgroup labels are purely for structure; the user cannot select these as values.

Example 2

The following code shows how to creating groups of options with a disabled option.


<html>
<body>
  <form action="" method="get" name="frmInfo">
    Please select the product you are interested in:<br /> <select
      name="selInformation">
      <option disabled="disabled" value="">-- Hardware --</option>
      <option value="Desktop">Desktop computers</option>
      <option value="Laptop">Laptop computers</option>
      <option disabled="disabled" value="">-- Software --</option>
      <option value="OfficeSoftware">Office software</option>
      <option value="Games">Games</option>
      <option disabled="disabled" value="">-- Peripherals --</option>
      <option value="Monitors">Monitors</option>
      <option value="InputDevices">Input Devices</option>
      <option value="Storage">Storage</option>
    </select> <br />
    <br />
    <input type="submit" value="Submit" />
  </form><!--from w  w  w .  j  a  v  a  2  s . co m-->
</body>
</html>

Click to view the demo





















Home »
  HTML CSS »
    HTML »




HTML Introduction
HTML Document
HTML Section
HTML Group Content
HTML Text Marker
HTML Table
HTML Form
HTML Embed