2

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> 
JDandChips
  • 9,780
  • 3
  • 30
  • 46
ah gal
  • 279
  • 2
  • 7
  • 19
  • Do you just want the background of the `optgroup` to be highlight in some way? – hungerstar Apr 25 '15 at 04:06
  • optgroup is not clickable. though you can get the same effect using only option tags and css. see http://stackoverflow.com/questions/9892247/selectable-optgroup-in-html-select-tag – gp. Apr 25 '15 at 04:24
  • hi hungerstar. yes. i want the optgroup (which is the Swedish Cars) to be highlighted in the dropdown. – ah gal Apr 25 '15 at 04:44

3 Answers3

1

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/

milesholt
  • 161
  • 1
  • 9
0

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/

JDandChips
  • 9,780
  • 3
  • 30
  • 46
0

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>
Wolfzmus
  • 463
  • 1
  • 10
  • 23