如何在运行时禁用select2中的选项

时间:2017-12-11 14:40:58

标签: javascript performance dom jquery-select2

在select2(版本4.0.x)中,我找不到在运行时禁用选项的简单方法。 到目前为止,最好的解决方案是调用destroy并重新创建select2。即使这样可行,但我担心它会在我的生产环境中产生太多的性能损失,并且有多个选项和大量选项。作为奖励,我在重新创建动作期间因为绑定事件(不在小提琴中)而从select2获得错误。

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

要触发此问题,请逐个打开所有选项。 然后单击切换按钮。 然后再次查看选择。

  • first select始终保持第一个打开状态。
  • 第二次选择需要在更新前打开两次。
  • 第三个选择(销毁)是唯一可以按需运行的选项。

相关问题:How to disable options in select2

除了重新创建之外,我还尝试触发更改事件并向子树添加伪造选项,所有这些都有效,但不会更新现有的列表项。

1 个答案:

答案 0 :(得分:0)

如果您的数据不是很大,我认为这是一个很好的解决方案。

//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
    });
});