我正在创建一个包含两个选择元素的简单表单。两个选择元素中的每一个都有一些选项,在这些选项中有一些值。 id为“average”的第一个选择有五个选项。 id为“amount”的第二个有三个选项。我想要的是,如果用户从“平均”中选择具有值“D”的选项,则禁用“金额”中的所有选项,并且仅可用于选择值为“30”的选项”。我尝试了一些东西,但它没有用。希望有人可以帮助解决这个问题。
由于
HTML
<form action="#" method="post">
<select id="average">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D" id="special">D</option>
<option value="E">E</option>
</select>
<select id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30" id="onlyAmount">30</option>
</select>
</form>
的JavaScript
var myAverage = document.querySelector("#average");
var mySpecial = document.querySelector("#special");
var myAmount = document.querySelector("#amount");
var onlyAmount = document.querySelector("#onlyAmount");
if( mySpecial.value.selected ) {
for ( var i = 0; i < myAmount.children.length; i++ ) {
myAmount[i].disabled = true;
}
onlyAmount.disabled = false;
}
答案 0 :(得分:2)
<html>
<head>
</head>
<body>
<form action="#" method="post">
<select id="average">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D" id="special">D</option>
<option value="E">E</option>
</select>
<select id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30" id="onlyAmount">30</option>
</select>
</form>
<script type="text/javascript">
(function(){
var myAverage = document.querySelector("#average");
var mySpecial = document.querySelector("#special");
var myAmount = document.querySelector("#amount");
var onlyAmount = document.querySelector("#onlyAmount");
myAverage.addEventListener('change', function(){
debugger;
if( myAverage.value === 'D' ) {
myAmount.value = "";
for ( var i = 0; i < myAmount.children.length; i++ ) {
myAmount[i].disabled = true;
}
onlyAmount.disabled = false;
}else{
for ( var i = 0; i < myAmount.children.length; i++ ) {
myAmount[i].disabled = false;
}
}
})
})();
</script>
</body>
</html>
这是一个有效的Plunkr
https://plnkr.co/edit/gXW4azAqKPWwsrUoNwak?p=preview
希望这有帮助
答案 1 :(得分:1)
使用addEventListener
检查用户从下拉列表中选择新项目。然后,您可以调用函数以根据原始代码应用逻辑。
var myAverage = document.querySelector("#average");
var mySpecial = document.querySelector("#special");
var myAmount = document.querySelector("#amount");
var onlyAmount = document.querySelector("#onlyAmount");
myAverage.addEventListener('change', analyseUserSelection);
function analyseUserSelection(e) {
if (mySpecial.selected) {
for (var i = 0; i < myAmount.children.length; i++) {
myAmount[i].disabled = true;
}
onlyAmount.disabled = false;
}
}
<form action="#" method="post">
<select id="average">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D" id="special">D</option>
<option value="E">E</option>
</select>
<select id="amount">
<option value="10">10</option>
<option value="20">20</option>
<option value="30" id="onlyAmount">30</option>
</select>
</form>