单击Optgroup并选择/取消选择Bootstrap 4.0的选项

时间:2019-05-31 14:32:56

标签: jquery html bootstrap-4 bootstrap-select

我正在尝试选择/取消选择optgroup,以选择其中的所有选项。我正在使用这个'https://github.com/snapappointments/bootstrap-select'库。

我尝试在下面添加以下代码:“ clickListener:function(){”,该文件可以在bootstrap-select.js文件中找到,但失败了。以下是我尝试添加的内容。对于我使用的bootstrap-select.js文件的副本,请在此问题的末尾找到链接,因为由于堆栈溢出300,000个字符限制而无法上传整个文件。

// I have tried adding code below under this: '<b>clickListener: function() {</b>' which can be found in the bootstrap-select.js file but failed:
this.$newElement.find('li').on('click', function(e) {
  e.preventDefault();
  console.log('Bootstrap-Select.js - line #1438');
  var base = $(this).closest(".bootstrap-select");
  var select = base.find("select");

  // check if this .dropdown-header is part of bootstrap-select AND multiple or not
  if (base.length && select.prop("multiple")) {

    var group = $(this).data("optgroup") - 1;
    var group2 = group + 1;
    var select = $(this).closest(".bootstrap-select").find("select");

    if ($(this).hasClass("dropdown-header")) {

      if (base.find("li[data-optgroup=" + group2 + "]:not(.selected)").length === 1)
        $(this).closest(".bootstrap-select").find("select > optgroup:eq(" + group + ") > option").prop("selected", false);
      else
        $(this).closest(".bootstrap-select").find("select > optgroup:eq(" + group + ") > option").prop("selected", true);

      select.selectpicker('render');
      //select.change();
    }
  }
});
<!DOCTYPE html>
<html>

<head>
  <title>Bootstrap-select Tests (Bootstrap 4)</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.9/css/bootstrap-select.css">
  <style>
    body {
      padding-top: 70px;
    }
  </style>
</head>

<body>
  <select class="selectpicker" multiple data-live-search="true">
    <optgroup label="Fruit">
      <option>Apple</option>
      <option>Orange</option>
    </optgroup>
    <optgroup label="Vegetable">
      <option>Corn</option>
      <option>Carrot</option>
    </optgroup>
  </select>
  <!-- To be continued -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
  <script src="../dist/js/bootstrap-select.js"></script>
</body>

</html>

bootstrap-select.js文件的副本位于此处(由于文件超过StackOverflow的300000个字符限制,因此无法添加): https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.9/js/bootstrap-select.js

0 个答案:

没有答案