简体   繁体   English

使用 jQuery 禁用多个 select2 字段

[英]Disable multiple select2 field with jQuery

I create a checkbox field and multiple select2 field, and I enable the checkbox field but which change is not affect the multiple select field.我创建了一个复选框字段和多个 select2 字段,并启用了复选框字段,但哪个更改不会影响多选字段。 I need to disable the multiple select field after disabling the checkbox.禁用复选框后,我需要禁用多选字段。 is this possible?这可能吗? I tried the below code.我尝试了下面的代码。

$('select option').prop("disabled", true);

disable select2 using $(".sel2").prop("disabled", true) for more detail see the document https://select2.org/appearance使用$(".sel2").prop("disabled", true)禁用 select2 以获取更多详细信息,请参阅文档https://select2.org/appearance

 $(document).ready(function() { $('.sel2').select2(); }); $(document).on('click','#disable',function() { if ($(this).prop("checked")) { //console.log("in"); $(".sel2").prop("disabled", true); } })
 <link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script> <select class="sel2" name="state"> <option value="AL">one</option> <option value="AL">two</option> </select> <select class="sel2" name="state"> <option value="AL">one</option> <option value="AL">two</option> </select> <select class="sel2" name="state"> <option value="AL">one</option> <option value="AL">two</option> </select> <input type="checkbox" id="disable" value="Disable select" /> Disable
if you want to enable and disable select2 fields on checked and unchecked of check box 如果要在选中和取消选中复选框时启用和禁用 select2 字段

$(document).on('click','#disable',function() { if ($(this).prop("checked")) { $(".sel2").prop("disabled", true); }else{ $(".sel2").prop("disabled", false); } })

You are currently refering to specific options of the select, I think you need to target the parent select element.您当前指的是选择的特定选项,我认为您需要针对父选择元素。

And according to the documentation , see Select2 Disabled Mode , you need to do it like this:根据文档,请参阅Select2 Disabled Mode ,您需要这样做:

$("select").select2("enable", false);

Nvm, I see I mentioned the old documentation, parent element thing was correct. Nvm,我看到我提到了旧文档,父元素是正确的。

$("#disable").change(function() {

  if ($(this).is(":checked")) {
    $("select").attr('disabled', 'disabled');
  }
})

you can use is checked to checking if checkbox is cecked or not您可以使用 is 检查检查复选框是否被选中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM