我想用 select2 来获取用户的偏好。选择一个选项后,其他 select2 中的选项应禁用。
Sample:
偏好 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();
});
希望我的理解是对的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)