Multiselect Box with Optgroups: Select one per group

可紊 提交于 2020-01-12 07:50:12

问题


I have a selectbox with the multiple attribute set. I'm also using <optgroup> tags to separate categories within my select box. I'm looking for a way, using either javascript or jQuery, to have the various options within each group to behave with 'radio button logic' rather than 'check box 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>
  1. User selects item 1.1 in the list. item 1.1 is selected as expected.
  2. User selects item 2.1 in the list. Now both item 1.1 and item 2.1 are selected.
  3. User selects item 1.2 in the list. Now item 1.1 is deselected, while item 2.1 and item 1.2 are both selected.

Does that make sense? Thanks in advance!


回答1:


$('#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, truth be told, if you want "radio button logic", you might consider not using a multiple select box. Usability with multiple select boxes is a pain anyway (people have to ctrl-click to select more than one option). Consider using radio buttons, or using a single-select box for each group. Both are harder to mess up. And they work without JS, which is pretty much always a plus.



来源:https://stackoverflow.com/questions/9984849/multiselect-box-with-optgroups-select-one-per-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!