我有很多下拉列表,我希望如果我选择一个值,我想在其他下拉列表中禁用它,例如,如果我在select1中选择Test,在select2中选择Test 2,我应该在select3中禁用测试1和测试2
这是我的剧本
$( document ).ready(function() {
var player_selected = [];
function checkPlayerSelected(){
player_selected = [];
$('select').each(function(){
if($(this).val() != "0"){
player_selected.push($(this).val());
}
});
}
$('select').change(function(){
checkPlayerSelected();
console.log(player_selected);
$(this).siblings('select').children('option').each(function() {
if(jQuery.inArray($(this).val(), player_selected)){
$(this).attr('disabled', true);
}
});
});
});
</script>
</head>
<body>
<select id="select1" name="select1">
<option value="0">No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select id="select2" name="select2">
<option value="0">No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<select id="select3" name="select3">
<option value="0">No Match</option>
<option value="1">Test</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
</body>
</html>
编辑:
$( document ).ready(function() {
var player_selected = [];
function checkPlayerSelected(){
player_selected = [];
$('select').each(function(){
if($(this).val() != "0"){
player_selected.push($(this).val());
}
});
}
$('select').change(function(){
checkPlayerSelected();
console.log(player_selected);
$(this).siblings('select').children('option').each(function() {
$(this).removeAttr('disabled', true);
if(jQuery.inArray($(this).val(), player_selected) >-1){
$(this).attr('disabled', true);
}
});
});
});
我尝试再次启用,如果我更改了值,但是当我选择测试时仍然有问题 - 测试2 - 测试3在第二个下拉列表中“测试”启用我不知道为什么
答案 0 :(得分:0)
你非常接近,除了-1
返回数组索引或-1
如果找不到。
您需要与if
中的0
进行比较,因为if(jQuery.inArray($(this).val(), player_selected))
是有效索引,但在条件
更改
if(jQuery.inArray($(this).val(), player_selected) >-1)
要
data
的 DEMO 强>