I have a select dropdown with many options, and they need to be grouped, because I am giving each <optgroup>
a class and setting them to display:none
, so that when I select something in another select dropdown for them to become visible. My problem is that I seem to HAVE to use a label, and I really do not want a label. My options list is going to be so long so to insert a class inside each option is going to be a problem, especially with my using Jquery to manipulate them. How can I group them instead? I just can't find a solution anywhere.
HTML example:
<select>
<option>Select something</option>
<optgroup class="default" label="defaultLabelNotwanted">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</optgroup>
<optgroup class="one" style="display:none" label="firstLabelNotWanted">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
<option>Option5</option>
<option>Option6</option>
</optgroup>
<optgroup class="two" style="display:none" label="secondLabelNotWanted">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
<option>Option5</option>
<option>Option1</option>
<option>Option6</option>
</optgroup>
<optgroup class="three" style="display:none" label="thirdLabelNotWanted">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
<option>Option5</option>
<option>Option6</option>
<option>Option7</option>
</optgroup>
<optgroup class="four" style="display:none" label="fourthLabelNotWanted">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
<option>Option4</option>
<option>Option5</option>
<option>Option6</option>
</optgroup>
The only permissible tags inside a <select>
are <option>
and <optgroup>
(https://html.spec.whatwg.org/multipage/form-elements.html#the-select-element), so no, there is no other way to group your options other than using an optgroup.
What you can do is move the class from the optgroup to its options, then move all the options directly under the select, and finally remove the optgroups.
$(document).ready(function () {
const select = $('select');
select.find('option').each(function () {
select.append($(this).addClass($(this).parent().attr('class')));
});
select.find('optgroup').remove();
});
you can then hide options based on class:
select.find('.two').hide();
jsfiddle: https://jsfiddle.net/ux2m6bhw/1/