jQuery - 单击optgroup选择所有子选项

时间:2016-07-15 15:04:50

标签: jquery html html-select optgroup

如何在html中点击的select标签中创建一个optgroup。单击此标签时,应选择其所有子选项。

示例:选择带有标签瑞典汽车的optgroup应自动选择沃尔沃和萨博选项。

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>

2 个答案:

答案 0 :(得分:1)

multiple元素具有$("optgroup").on("click", function() { $(this).children("option").prop("selected", "selected"); $(this).next().children("option").prop("selected", false); $(this).prev().children("option").prop("selected", false); });属性,用于选择多个值。

这是一种可能的解决方案。

在此代码中,如果您单击其中一个选项组标签,将自动选择所有子选项。

select {
  height: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select>
var pictureLibs = new List<string>();
foreach(var list in oWeb.Lists){
    if(list.BaseTemplate.Equals(SPListTemplateType.PictureLibrary))
    pictureLibs.Add(list.Title);
}

答案 1 :(得分:0)

首先为您的选择提供ID 例如

<select id="selectgroup">

然后将类添加到您的optgroup,如

  <optgroup label="Swedish Cars" class="select2-result-selectable">

然后添加此

$('#selectgroup').select2({

    }).on('select2-selecting', function (e) {
        debugger;
        var $select = $(this);
        if (e.val == undefined) {
            e.preventDefault();
            var childIds = $.map(e.choice.children, function (child) {
                return child.id;
            });
            $select.select2('val', $select.select2('val').concat(childIds));
            $select.select2('close');
       }
    });

如果您点击optgroup,那么它将选择optgroup下的所有选项。

相关问题