Select2:动态隐藏某些optgroup [英] Select2: Hide certain optgroup dynamically

查看:198
本文介绍了Select2:动态隐藏某些optgroup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要隐藏/显示某个选项组( <optgroup> )我有条件地尝试了这个问题的最佳解决方案- Select2:动态隐藏某些选项

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

它隐藏每个选项(根据需要),但是组标题保持可见,尽管它没有子项.如何在 select2 中隐藏整个选项组?

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?

推荐答案

我认为您只能使用数据数组源而不使用HTML中的选项来禁用Select2中的<optgroup>.

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

查看有关Select2 github存储库的问题:

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>

或者您可以检查以下jsfiddle: https://jsfiddle.net/beaver71/u0jekg44/

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

这篇关于Select2:动态隐藏某些optgroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆