【问题标题】:jQuery - Click on optgroup selects all child optionsjQuery - 单击 optgroup 选择所有子选项
【发布时间】:2016-07-15 15:04:50
【问题描述】:

如何在 html 中点击选择标签中的 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>

【问题讨论】:

    标签: jquery html html-select optgroup


    【解决方案1】:

    Select 元素具有用于选择多个值的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>

    【讨论】:

      【解决方案2】:

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

      &lt;select id="selectgroup"&gt;

      然后将类添加到您的 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 下的所有选项。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-27
        • 2017-04-05
        相关资源
        最近更新 更多