Multiselect Box with Optgroups: select one group at a time

I have a selectbox with a set of multiple attributes. I also use <optgroup> tags to separate categories in my selection box. I am looking for a way using javascript or jQuery so that the various parameters within each group are led with "switch logic" and not with "check logic". For example:

 <optgroup label="cat1"> <option>item 1.1</option> <option>item 1.2</option> </optgroup> <optgroup label="cat2"> <option>item 2.1</option> <option>item 2.2</option> </optgroup> 
  • The user selects item 1.1 in the list. item 1.1 is selected as expected.
  • The user selects item 2.1 in the list. Now select both item 1.1 and item 2.1 .
  • The user selects item 1.2 in the list. Now item 1.1 is canceled, and item 2.1 and item 1.2 are selected.

It makes sense? Thanks in advance!

+7
source share
1 answer
 $('#select-box-id optgroup option').click(function() { // only affects options contained within the same optgroup // and doesn't include this $(this).siblings().prop('selected', false); });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ 

Although, the truth is, if you need "switch logic", you can not use the multiple-choice field. Ease of use with multiple selection blocks is a pain anyway (people need to press Ctrl-click to select multiple options). Think about how to use the radio buttons or use the field for one choice for each group. Both are harder to ruin. And they work without JS, which is pretty much always a plus.

+6
source

All Articles