2
votes

I am planning to put a brief description page for the main car type (Swedish Cars). I also want to show that Volvo and Saab is under Swedish Cars in the dropdown. Then when I click on Volvo, it should navigate to the Volvo description page. How can I show the optgroup label as selected initially?

Thank you.

<select>
   <optgroup label="Swedish Cars">
     <option value="volvo">Volvo</option>
     <option value="saab">Saab</option>
   </optgroup>
</select> 
3
Do you just want the background of the optgroup to be highlight in some way? - hungerstar
optgroup is not clickable. though you can get the same effect using only option tags and css. see stackoverflow.com/questions/9892247/… - gp.
hi hungerstar. yes. i want the optgroup (which is the Swedish Cars) to be highlighted in the dropdown. - ah gal

3 Answers

1
votes

Another solution would be to have the first option being the same as the optgroup label, then hide it when the dropdown is in focus.

<div class="select-wrapper">
<select>
   <optgroup class="swe-car" label="Swedish Cars">
     <option value="swedish-cars">Swedish Cars</option>
     <option value="volvo">Volvo</option>
     <option value="saab">Saab</option>
   </optgroup>
</select> 
</div>

$().ready(function(){    
    $('select').focus(function(){
       $('select option').eq(0).hide();
    });
});

https://jsfiddle.net/atbqtnq8/13/

0
votes

I believe what you are asking for will render like this:

enter image description here

This is not strictly possible as you can't "select" the option group label. To get the effect you're looking for you'll have to perform a bit of trickery.

We can put a custom label into a span and absolutely position this span over the select to make the initial selection appear as the option group label. After that we need a little bit of javascript to fake the click and change event, which you can see a working example below. However, this is what your html will look:

<div class="select-wrapper">
 <span>Swedish Cars</span>
 <select>
  <optgroup class="swe-car" label="Swedish Cars">
   <option value="volvo">Volvo</option>
   <option value="saab">Saab</option>
  </optgroup>
 </select> 
</div>

https://jsfiddle.net/atbqtnq8/

0
votes

How about this? I copy answer from another question Selectable <optgroup> in HTML <select> tag

.optionGroup {
    font-weight: bold;
    font-style: italic;
}
    
.optionChild {
    padding-left: 15px;
}
<select>
    <option value="Swedish Cars" class="optionGroup">Swedish Cars</option>
    <option value="volvo" class="optionChild">volvo</option>
    <option value="saab" class="optionChild">saab</option>
</select>