根据第一个下拉菜单禁用第二个下拉选项 [英] Disable 2nd dropdown option based on first dropdown
问题描述
我有两个动态下拉菜单,但下拉菜单的值和选项都相同。我想要的是,如果用户从第一个下拉菜单中选择苹果,那么第二个下拉菜单的苹果选项将被禁用(使用JavaScript)。
//第一个下拉菜单
< option value =1> Apple< / option>
< option value =2>芒果< / option>
< / select>
//第二个下拉菜单
< select name =fruit2>
< option value =1> Apple< / option>
< option value =2>芒果< / option>
< / select>
我试过用jQuery:
function witness()
{
var op = document.getElementById(witness1)。value;
$('option [value ='+ op +']')。prop('disabled',true);
}
但是,这两个下拉菜单的值都被禁用,如果我选择芒果,未启用它保持禁用状态。我知道我没有通过ID,所以这两个下拉列表值都禁用,但我应该通过哪里?
如果用户选择苹果,然后在第二个下拉菜单苹果将被禁用,我想使用Javascript或jQuery来做这件事。
试试这个:
HTML:
< select id ='fruit1'onchange =witness();>
< option selected>< / option>
< option value =1> Apple< / option>
< option value =2>芒果< / option>
< / select>
< select id ='fruit2'>
< option selected>< / option>
< option value =1> Apple< / option>
< option value =2>芒果< / option>
< / select>
JQuery:
function witness(){
$(#fruit2 option)。each(function(){
if($(#fruit1 option:selected).val()= = $(this).val())
$(this).attr(disabled,disabled);
else
$(this).removeAttr(disabled) ;
});
$ / code $
您可以在这里看到一个工作例子:
https://jsfiddle.net/mqjxL4n0/
I have two dynamic dropdowns but both dropdown's value and options are same. What I want that if user select 'apple' from first dropdown then the second dropdown's apple option will be disabled (using javascript). In short user can not select same value from both.
//first drop down
<select name="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
//second dropdown
<select name="fruit2">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
I have tried with jQuery:
function witness()
{
var op=document.getElementById("witness1").value;
$('option[value='+op+']').prop('disabled', true);
}
But with this both dropdown's value are disabled and if I select mango then apple will not enabled it remains disabled. I know I did not pass id so both dropdown value are disabled but where should i pass ?
If user select apple then in second dropdown apple will be disabled, I want to do this using Javascript or jQuery.
解决方案 Try this out:
HTML:
<select id='fruit1' onchange="witness();">
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<select id='fruit2'>
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
function witness(){
$("#fruit2 option").each(function(){
if($("#fruit1 option:selected").val() == $(this).val())
$(this).attr("disabled", "disabled");
else
$(this).removeAttr("disabled");
});
}
You can see a working exemple here:
https://jsfiddle.net/mqjxL4n0/
这篇关于根据第一个下拉菜单禁用第二个下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!