簡體   English   中英

如何在運行時禁用select2中的選項

[英]How to disable options in select2 at runtime

在select2(版本4.0.x)中,我找不到在運行時禁用選項的簡單方法。 到目前為止,最好的解決方案是調用destroy並重新創建select2。 即使這行得通,但恐怕它會給我的生產環境帶來過多的性能影響,因為它會產生多種選擇和大量選項。 另外,由於綁定事件(不在小提琴中),我在recreate操作期間從select2中得到了錯誤。

檢查小提琴: https : //jsfiddle.net/c3ubx018/

要觸發問題,請打開所有選項,一一選擇。 然后單擊切換按鈕。 然后再次查看選擇。

  • 第一次選擇始終保持第一次打開的狀態。
  • 第二個選擇需要兩次打開才能更新。
  • 第三選擇(銷毀)是唯一按要求工作的選擇。

相關問題: 如何禁用select2中的選項

除了重新創建之外,我還嘗試了觸發change事件並向子樹中添加了一個偽造的選項,所有這些選項均有效,但不會更新現有列表項。

如果您的數據不是很大,我認為這是一個很好的解決方案。

//create select2 data inside array
select2_data=[
    {"id":1,"text":"A","disabled":false},
    {"id":2,"text":"B","disabled":false},
    {"id":3,"text":"C","disabled":false}
];
//initialize select2
$("#my_select2").select2({
    data:select2_data
});
//After any event you can do this process
//For Now, We disabled the selected option and enable all other options
$("#my_select2").on('select2:select', function (e) { 
    //change data inside our array
    for (let i = 0, il=select2_data.length; i < il; i++) {
        id=$(this).val();//return selected option id
        if(select2_data[i]["id"]==id){//disable selected item
            select2_data[i]["disabled"]=true;
        }else{//enable all other option in select2
            select2_data[i]["disabled"]=false;
        }           
    }
    //now empty select2 and reinitialized it.
    $('#my_select2').empty().select2({
        data:select2_data
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM