首页 > 解决方案 > 使用 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(); 
     })

标签: jqueryeventsbootstrap-4bootstrap-multiselect

解决方案


试试这个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>

推荐阅读