Skip to content Skip to sidebar Skip to footer

Making Optgroup Label As Selected In Dropdown

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

Solution 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><optgroupclass="swe-car"label="Swedish Cars"><optionvalue="swedish-cars">Swedish Cars</option><optionvalue="volvo">Volvo</option><optionvalue="saab">Saab</option></optgroup></select> 
</div>

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

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

Solution 2:

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:

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

https://jsfiddle.net/atbqtnq8/

Solution 3:

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><optionvalue="Swedish Cars"class="optionGroup">Swedish Cars</option><optionvalue="volvo"class="optionChild">volvo</option><optionvalue="saab"class="optionChild">saab</option></select>

Post a Comment for "Making Optgroup Label As Selected In Dropdown"