Select2: Hide certain optgroup dynamically

别来无恙 提交于 2019-12-12 20:43:12

问题


I need to hide/show a certain option group (<optgroup>) conditionally and I've tried the top solution from this question - Select2: Hide certain options dynamically

It hides every option (as required), but group title stays visible, although it has no child items. How to hide the whole option group in select2?


回答1:


I think you can disable <optgroup> in Select2 only using data array source, not using options in HTML.

See issues on Select2 github repo:

  • https://github.com/select2/select2/issues/4876
  • https://github.com/select2/select2/pull/5035

Here is a snippet which exemplifies the two approach:

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>

Or you can check this jsfiddle: https://jsfiddle.net/beaver71/u0jekg44/



来源:https://stackoverflow.com/questions/48078990/select2-hide-certain-optgroup-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!