user882670
user882670

Reputation:

Display subcategories in HTML select box

I have the following categories displayed in a select box:

<form>
    <select class="favoritefood">
        <optgroup label="Dairy products">
            <option>Cheese</option>
            <option>Egg</option>

        </optgroup>
        <optgroup label="Vegetables">
            <option>Cabbage</option>
            <option>Lettuce</option>
            <option>Beans</option>
            <option>Onions</option>
            <option>Courgettes</option>

        </optgroup>
    </select>
</form>

Is there any way to go another level down, ie, a subcategory? I've tried using optgroup inside optgroup but it doesn't work.

Upvotes: 2

Views: 8337

Answers (3)

Lucky Soni
Lucky Soni

Reputation: 6888

You should create a custom dropdown for this purpose. Here are the steps:

  1. Hide the original dropdown with CSS (display:none;) OR create a hidden field that will contain the value selected by the user

    <input type="hidden" name="selection" id="selection">

  2. Create a unordered list (ul) with as many nested li and sub ul

    <ul class="custom-drop">
        <li class="option-group">
             <ul>
                <li class="heading">Vegetables</li>
                <li>Cabbage</li>
             </ul>
        </li>
        <li class="option-group">
             <ul>
                <li class="heading">Dairy products</li>
                <li>Cheese</li>
             </ul>
        </li>
    </ul>
    
  3. Style this newly created ul as per your needs

  4. Listen for the click event on li inside this ul and set the appropriate option inside the hidden dropdown OR set the value of hidden field so that it can be sent with the form.

So if you are using jQuery then do something like this:

$('body').on('click', '.custom-drop li', function() {
    $('#selection').val($(this).text());
    // Probably you want to handle showing/hiding the custom drop here
});

Upvotes: 1

Anonymous
Anonymous

Reputation: 1373

You cant go any deeper. It is not allowed for the optgroup. Read this: http://www.w3.org/TR/html401/interact/forms.html#h-17.6

Upvotes: 0

John Cz.
John Cz.

Reputation: 43

Or just put one or more spaces - &nbsp - before your text in the option.

Upvotes: 2

Related Questions