如何在select2中禁用选项

时间:2017-05-05 09:46:20

标签: jquery jquery-select2

我想用select2取用户的偏好。选择一个选项后,其他select2中的选项应禁用。

样品:

偏好1: 选项1 选项2 选项3 备选方案4

偏好2: 选项1 选项2 选项3 备选方案4

偏好3: 选项1 选项2 选项3 备选方案4

偏好4: 选项1 选项2 选项3 备选方案4

如果我在首选项1中选择选项1,则应在首选项1,2,3,4中禁用 如果我在首选项2中选择选项2,则应在首选项1,2,3,4中禁用 如果我在首选项3中选择选项3,则应在首选项1,2,3,4

中禁用

再次,如果我在首选项2中选择选项4,则应在首选项1,2,3,4中禁用,并且选项2应在首选项3和4中可供选择。

我已经厌倦了各种各样的实现但是卡住了帮助我。

HTML:

<div class="form-group col-md-6 m-t-sm">
    <label> Select Preference 1: </label>
    <select class="form-control" id="pref1" name="pref1" style="width:100%">
    <option value=""> Select Campus Preference 1 </option>
    <option value="N"> N </option>
    <option value="O"> O </option>
    <option value="R"> R </option>
    <option value="S"> S </option>
    </select>
    <label id="pref1-error" class="error" for="pref1"></label>
</div>
.
.
.

我目前的js:

$('select[name*="pref"]').change(function(){

    // start by setting everything to enabled
    $('select[name*="pref"] option').prop('disabled',false);

    // loop each select and set the selected value to disabled in all other selects
    $('select[name*="pref"]').each(function(){ 
        var $this = $(this);
        $('select[name*="pref"]').not($this).find('option').each(function(){
           if($(this).attr('value') == $this.val()){            
               $(this).prop('disabled',true);               
           }
        });
    });

});

1 个答案:

答案 0 :(得分:4)

您可以在禁用后重新初始化选择使用以下代码

$("select").select2("destroy").select2();

类似

$('select[name*="pref"]').change(function(){

    // start by setting everything to enabled
    $('select[name*="pref"] option').prop('disabled',false);

    // loop each select and set the selected value to disabled in all other selects
    $('select[name*="pref"]').each(function(){ 
        var $this = $(this);
        $('select[name*="pref"]').not($this).find('option').each(function(){
           if($(this).attr('value') == $this.val()){            
               $(this).prop('disabled',true);               
           }
        });
    });
    $('select[name*="pref"]').select2("destroy").select2();
});

希望我能帮到你

相关问题