启用/禁用下拉菜单 - Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5424806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enable/Disable dropdown - Javascript
提问by name_masked
I have the following code where 2 drop downs are available on the UI. When I select value "1" of drop down 1, the drop down 2 should be disabled. When I select value "1", the dropdown 2 is disabled. But I am not able to re-enable the drop down 2 when the user select value "2" from drop down 1. I am not sure since I am calling the performValidation()
method for onClick
event of both the options in drop down 1.
我有以下代码,其中 UI 上有 2 个下拉菜单。当我选择下拉列表 1 的值“1”时,下拉列表 2 应该被禁用。当我选择值“1”时,下拉列表 2 被禁用。但是,当用户从下拉列表 1 中选择值“2”时,我无法重新启用下拉列表 2。我不确定,因为我正在调用下拉列表 1 中两个选项的事件performValidation()
方法onClick
。
Code:
代码:
<html>
<head></head>
<script = "text/javascript">
function performValidation()
{
if (document.mainForm.criteriaOne.value == "1")
{
document.mainForm.criteriaTwo.options.length = 0;
document.mainForm.criteriaTwo.disabled = true;
}
else
document.mainForm.criteriaTwo.disabled = false;
}
</script>
<body>
<form name="mainForm" action= "" method ="get">
Criteria One:<select id = "criteriaOne">
<option value = "1" onClick ="performValidation()"> Select One - One</option>
<option value = "2" onClick ="performValidation()"> Select one - Two</option>
</select>
Criteria Two:<select id = "criteriaTwo">
<option value = "1" onClick ="performValidation()"> Select Two - One</option>
</select>
</form>
</body>
</html>
回答by Andrew
You need to wire up a function to the onchange event on the select something like
您需要将一个函数连接到 select 上的 onchange 事件,例如
document.getElementById("criteriaOne").onchange = function()
{ // do some work to check the selectedIndex and determine whether to re- enable the other drop down}
回答by Duniyadnd
You don't necessarily need
你不一定需要
document.mainForm.criteriaTwo.options.length = 0;