简体   繁体   English

我如何删除或禁用select2中的项目

[英]How can i delete or disable items in select2

Hi I want to delete or disable first item of my select2 when my value(x) = 1 . 嗨,我想在我的value(x) = 1时删除或禁用select2的第一项。 How can I do this? 我怎样才能做到这一点? Thanks. 谢谢。

var myData= [
    {
        id: "id1",
        text: 'aaaaa'
    }, {
        id: "id2",
        text: 'bbbbb'
    }
            ];


var x=0;
if (x == '1') {
    $('.select2 option[value="' + myData[0]+ '"]').remove()
}

I'm assuming you're using jQuery select2 and you're creating your select2 element from myData . 我假设您正在使用jQuery select2,并且正在从myData创建select2元素。

If your data is a source of truth, you can do it this way to keep it updated and reflect that state in your DOM (what you see). 如果您的数据是事实的来源,则可以通过这种方式来使其保持最新状态并在DOM中反映该状态(您所看到的)。

Use .shift() . 使用.shift() to remove the first element from your data array. 从数据数组中删除第一个元素。

Then re-init your select2 element with new data. 然后使用新数据重新初始化select2元素。 Like this (full working code below): 像这样(下面的完整工作代码):

// condition > do something to select2 element's data
if (true) {
  // remove first data item from array
  myData.shift();

  // empty select2 element's data and re-init
  $(".select2").empty();
  $(".select2").select2({
    data: myData
  });
}

You can run this to see it working. 您可以运行此程序以查看其是否正常运行。 After the conditional is applied, only the 2nd data item in myData remains. 应用条件后,仅保留myData中的第二个数据项。

If this solves your problem, let me know by accepting answer :) 如果这可以解决您的问题,请接受答案以让我知道:)

 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/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://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script> <select class="select2"> </select> <script> $(document).ready(function() { // data var myData = [ { id: "id1", text: "aaaaa" }, { id: "id2", text: "bbbbb" } ]; // your select2 element already exists $(".select2").select2({ data: myData }); // condition > do something to select2 element's data if (true) { // remove first data item from array myData.shift(); // empty select2 element's data and re-init $(".select2").empty(); $(".select2").select2({ data: myData }); } }); </script> 

From MDN : The shift() method removes the first element from an array and returns that removed element. MDN开始 :shift()方法从数组中删除第一个元素,然后返回删除的元素。 This method changes the length of the array. 此方法更改数组的长度。

<select name="carlist" form="carform">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>

If you want to remove volvo from select option use this 如果要从选择选项中删除沃尔沃,请使用此选项

$("select option[value='volvo']").remove()

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

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