Search code examples
htmlselectdrop-down-menu

How can I show a category name in html dropdown list?


I have a dropdown list in a form. There are many items. I want to show the category names in the dropdown list which the users will be able to see but won't be able to select.

So far I have this. But obviously it is not working.

<select id="item_name" name="item_name">
                    <dl>
                        <dt>Category 1</dt>
                            <dd><option value="1">Item 1</option></dd>
                            <dd><option value="2">Item 2</option></dd>
                            <dd><option value="3">Item 3</option></dd>
                        <dt>Category 2</dt>
                            <dd><option value="4">Item 4</option></dd>
                            <dd><option value="5">Item 5</option></dd>
                            <dd><option value="6">Item 6</option></dd>
                    </dl>
                </select>

Solution

  • You need to use optgroup elements:

    <select>
        <optgroup label="Category 1">
            <option>Item 1</option>
            <option>Item 2</option>
        </optgroup>
        <optgroup label="Category 2">
            <option>Item 3</option>
            <option>Item 4</option>
        </optgroup>
    </select>