how to let jquery select2 disable one option dynamically?

我怕爱的太早我们不能终老 提交于 2019-12-07 18:05:15

问题


I have some multiselect and i use jquery select2.I want to disable one option in other multiselect when this option is selected in one multiselect. i write this code,but it does work.

$("select.multiselect").on("change", function(e) {
    if(e.added){
        for(var i=0;i<this.options.length;i++){
            var vals = $(this).select2("val");
            for(var j=0;j<vals.length;j++){
                if(this.options[i].value===vals[j]){
                    this.options[i].selected=true;
                }
            }
        };
    }

    if(e.removed){
        for(var i=0;i<this.options.length;i++){
            if(this.options[i].value===e.removed.id){
                this.options[i].selected=false;
            }
        };
    }
});

how to do it?


回答1:


It was more complicated then I thought but here is what I came up with:

$('select.multiselect').on('change', function(e) {

    // the selected values
    var vals = $(this).select2("val");

    // selects contains all the OTHER select forms
    var selects = $('select').not('#'+$(this).attr('id'));

    // loop trough all the selects
    for (var i = 0; i < selects.length; i++) {
        //re-enable all options before
        $(selects[i]).find('option').removeAttr('disabled');
        // loop trough all the values
        for (var j = 0; j < vals.length; j++) {
            // disabled attribute
            $(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
        }
    }
});

Here's a fiddle if you want to see the result in action

Make sure all your select elements have a unique id.



来源:https://stackoverflow.com/questions/21909391/how-to-let-jquery-select2-disable-one-option-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!