带选组的多选框:每组选择一个 [英] Multiselect Box with Optgroups: Select one per group
问题描述
我有一个带有多个
属性集的选择框。我也使用< optgroup>
标签来分隔我的选择框内的类别。我正在寻找一种方法,使用javascript或jQuery,使每个组中的各种选项与单选按钮逻辑而不是复选框逻辑相似。例如:
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>
- 用户选择
item 1.1
在列表中。项目1.1
按预期选择。 - 用户选择列表中的
项目2.1
。现在选择项目1.1
和项目2.1
。 - 用户选择
item 1.2
在列表中。现在项目1.1
被取消选择,而项目2.1
和项目1.2
都被选中。
- User selects
item 1.1
in the list.item 1.1
is selected as expected. - User selects
item 2.1
in the list. Now bothitem 1.1
anditem 2.1
are selected. - User selects
item 1.2
in the list. Nowitem 1.1
is deselected, whileitem 2.1
anditem 1.2
are both selected.
这是否有意义?提前致谢!
Does that make sense? Thanks in advance!
推荐答案
$('#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);
});
虽然说实话,如果你想要单选按钮逻辑,你可能会考虑不使用多选框。无论如何,多个选择框的可用性是一个痛苦(人们必须按住Ctrl键单击以选择多个选项)。考虑使用单选按钮,或为每个组使用单选框。两者都难以搞砸。他们工作没有JS,这几乎总是一个加分。
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.
这篇关于带选组的多选框:每组选择一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!