Select2:动态隐藏某个optgroup

时间:2018-01-03 14:06:12

标签: hide jquery-select2 jquery-select2-4 optgroup

我需要有条理地隐藏/显示某个选项组(<optgroup>),我已经尝试过这个问题的最佳解决方案 - Select2: Hide certain options dynamically

它隐藏了每个选项(根据需要),但组标题保持可见,但它没有子项。如何隐藏select2中的整个选项组?

1 个答案:

答案 0 :(得分:0)

我认为您可以仅使用数据阵列源禁用Select2中的<optgroup>,而不是使用HTML中的选项。

请参阅Select2 github repo上的问题:

这是一个片段,举例说明了这两种方法:

var data = [{
  text: 'group1',
  children: [{
    id: '1',
    text: 'option 1'
  }, {
    id: '2',
    text: 'option 2',
    disabled: false,
  }, {
    id: '3',
    text: 'option 3',
    disabled: true,
  }]
},
{
  text: 'group2',
  disabled: true,
  children: [{
    id: '4',
    text: 'option 4',
    disabled: true,
  }, {
    id: '5',
    text: 'option 5'
  }]
}];

$(document).ready(function() {
  $('#test').select2({  data: data, });
  $('#test2').select2();
});

var group2Disabled = true;

toggleGroup2 = function() {
	group2Disabled = !group2Disabled;
  console.log("toggleGroup2", group2Disabled);
  var gr2 = data.find(findGroup2);
  gr2.disabled = !gr2.disabled;
  $('#test').empty().select2({data:data}).trigger("change");
}

function findGroup2(el) { 
    return el.text === 'group2';
}
select {
  width: 40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>

<label>Select List #1 (data)</label>
<select id="test"></select>
<button onclick="toggleGroup2()">toggle disable Group2</button>

<br><br><br>

<label>Select List #2 (html)</label>
<select id="test2">
  <optgroup label="group1">
    <option>option 1</option>
    <option>option 2</option>
    <option disabled="true">option 3</option>
  </optgroup>
  <optgroup label="group2" disabled="true">
    <option disabled="true">option 4</option>
    <option>option 5</option>
  </optgroup>
</select>

或者你可以查看这个jsfiddle:https://jsfiddle.net/beaver71/u0jekg44/