当用户开始在文本字段中输入内容时,我希望能够禁用页面上的选择菜单。这是因为文本字段是输入数据的另一种方式,禁用下拉菜单将有助于使其更加清晰。
我知道我可以用这个:
<select name="specialty" id="specialty" disabled="disabled">
永久禁用选择,但是有没有办法在文本字段的值更改时动态分配该属性?我知道没有 css 属性可以像文本输入和文本区域那样执行此操作。
我发现了一个 JQuery 解决方案,用于禁用选择中的选项:
Disable select options based on value *through the HTML only!*
我尝试修改它以禁用整个选择,但没有成功(文本字段的 ID 是 testinput):
<script type="text/javascript">
$("#testinput").change(function(){
$("#specialty").attr("disabled","disabled");
}
);
</script>
这是一个简化版本(真正的函数应该检查 testinput 中字符串的长度,并根据该长度决定是否禁用或启用选择),但如果有人可以帮助我实现此功能,那么修改它很容易.
最佳答案
对于最新的jquery版本,需要使用prop()而不是attr()。
$('#specialty').prop('disabled', true);
您还可以使用 focusin() 和 focusout() 函数来实现此目的。
//disable dropdown when entering text
$('#testinput').focusin(function(){
$('#specialty').attr('disabled',true);
});
//enable dropdown only if nothing entered
$('#testinput').focusout(function(){
if($('#testinput').val().length == 0){
$('#specialty').attr('disabled',false);
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table>
<tr>
<td>Input: <input type="text" id="testinput"></td>
<td>
<select name="specialty" id="specialty">
<option value="">--Select--</option>
</select>
</td>
</tr>
</table>
</body>
</html>
关于javascript - 根据文本字段值动态禁用选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9537492/