我有一个select
框,其中包含多个optgroup
:
<select id="g1" class="select" multiple="multiple">
<option></option>
<optgroup label="Group 1">
<option value="1">Title 1 A</option>
<option value="2">Title 1 B</option>
<option value="3">Title 1 C</option>
</optgroup>
<optgroup label="Group 2">
<option value="4">Title 2 A</option>
<option value="5">Title 2 B</option>
<option value="6">Title 2 C</option>
</optgroup>
</select>
我需要将selectbox限制为每个optgroup一个选项,替换之前选择的选项,例如:
如果我选择&#34;标题1 A&#34;来自第一个optgroup和&#34; Title 2 A&#34;从第二个optgroup,然后我选择&#34; Title 1 C&#34;从第一个optgroup开始,结果为&#34; Title 1 C&#34;和&#34;标题2 A&#34;。
我使用的是Select2 v4.0.3。
我找到了这个解决方案:Limit select2 selections by group 但适用于Select2 v3.5.2并且它与新版本不兼容。
答案 0 :(得分:0)
好的,我想出了一个你可以适应的解决方案。 Optgroups没有参与,但无论如何都应该工作。
HTML:
<select multiple style="width: 300px">
<option groupid="a" value="A_AK">Alaska</option>
<option groupId="b" value="B_HI">Hawaii</option>
<option groupid="c" value="C_CA">California</option>
<option groupid="a" value="D_NV">Nevada</option>
<option groupid="b" value="A_OR">Oregon</option>
<option groupid="c" value="B_WA">Washington</option>
<option groupid="a" value="C_AZ">Arizona</option>
<option groupid="b" value="D_CO">Colorado</option>
<option groupid="c"value="A_ID">Idaho</option>
<option groupid="a" value="B_MT">Montana</option>
<option groupid="b" value="C_NE">Nebraska</option>
<option groupid="c" value="D_NM">New Mexico</option>
<option groupid="a" value="A_ND">North Dakota</option>
<option groupid="b"value="B_UT">Utah</option>
<option groupid="c" value="C_WY">Wyoming</option>
</select>
您会注意到我添加了组ID属性。这用于建立选项之间的关系。
JavaScript:
$(function() {
$('select').select2({
allowClear: true,
placeholder: "Pick a State"
});
//Select2 Event handler for selecting an item
$('select').on("select2:selecting", function(evt, f, g) {
disableSel2Group(evt, this, true);
});
// Select2 Event handler for unselecting an item
$('select').on("select2:unselecting", function(evt) {
disableSel2Group(evt, this, false);
});
});
// At some point during the select2 instantation it created the
// data object it needs with the source select option.
// This function, called by the events above to set the current status for the
// group for which the selected option belongs.
function disableSel2Group(evt, target, disabled) {
// Found a note in the Select2 formums on how to get the item to be selected
var selId = evt.params.args.data.id;
var group = $("option[value='" + selId + "']").attr("groupid");
var aaList = $("option", target);
$.each(aaList, function(idx, item) {
var data = $(item).data("data");
var itemGroupId = $("option[value='" + data.id + "']").attr("groupid");
if (itemGroupId == group && data.id != selId) {
data.disabled = disabled;
}
})
}