如何禁用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);               
           }
        });
    });

});
达瓦尔在这方面

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

$("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();
});

希望我对你正确

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章