jquery - 使用 optgroup 引导多选下拉菜单
问题描述
我有一个下拉列表如下
<select class="selectpicker" multiple>
<optgroup label="option 1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</optgroup>
<optgroup label="option 2">
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</optgroup>
</select>
我只想从一个 optgroup 中选择,当我尝试从另一个 optgroup 中选择选项时,如果一个 optgroup 已经选择了一个选项,则需要取消选择/不允许选择。我尝试了 changed.bs.select 事件来获取 opt 组索引,但不知道如何实现这一点,有什么帮助吗?
$dropdown.on("changed.bs.select", "select", function (){
var $option = $(this).find("option:selected", this);
var optGroup = $option.closest("optgroup").index();
})
解决方案
试试这个http://jsfiddle.net/g9byn80a/
<select id="msel" style="width:300px">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
</select>
<script>
var memoryOne;
$("option").mouseover(function () {
var selectedOne = $("optgroup:nth-of-type(1)").children("option:selected").index();
memoryOne = selectedOne;
}).click(function () {
var theSelectedIndex = $(this).index();
var theParentIndex = $(this).parent().index();
setTimeout(function () {
clickEvent(theSelectedIndex, theParentIndex, memoryOne);
}, 1);
});
function clickEvent(passedIndex, parentIndex, memoryOne, memoryTwo) {
var selectionOne = memoryOne;
var theParent = $("optgroup:eq(" + parentIndex + ")");
var theOption = $("optgroup:eq(" + parentIndex + ") option:eq(" + passedIndex + ")");
var theGrandParent = $("select");
theParent.find("option:not(option:eq(" + passedIndex + "))").prop("selected", false);
}
</script>
推荐阅读
- asp.net - ASP.NET MVC 在 ElasticBeanStalk AWS 上不起作用
- f# - 在 Fsharp.Data JsonProvider 中解析混合类型
- r - 汇总 R 中的多个字段并抑制小于 x 的值
- r - 无法使用 observeEvent 和 eventReactive 更新闪亮应用程序中的输入
- google-cloud-platform - 使用 gcsfuse 安装在 Compute Engine 实例上的 Google Cloud Bucket 不会创建文件
- c++ - C++ 嵌套的 try-catch 捕获相同的异常 - 我应该如何重写这段代码?
- directx-11 - 将渲染目标视图设置为纹理直接 X 11 的一部分
- javascript - 从 Rails 视图中调用 javascript 函数的正确方法是什么?
- compiler-errors - Ada:'字符串由双引号字符分隔'编译错误
- javascript - Node-PostgreSQL 时间格式