我有一个文本框,旁边有一个提交按钮。该按钮处于禁用状态。一旦用户在文本框中输入内容,它就应该被启用。效果很好。但一旦用户开始输入,它就会被启用。如果使用退格键将字段清空,按钮仍保持启用状态。
<html>
<body>
<input type="text" id="fname" onkeyup="myFunction()">
<input type="button" id="a" disabled = "true" value ="click me">
<script>
function myFunction()
{
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
if(x.value != " ")
{
document.getElementById('a').disabled=false;
}
}
</script>
</body>
</html>
最佳答案
您应该在您的条件下添加 else 语句,以便在文本框为空时禁用按钮。尝试下面的代码。
<html>
<body>
<input type="text" id="fname" onkeyup="myFunction()">
<input type="button" id="a" disabled = "true" value ="click me">
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
if(x.value != "")
{
document.getElementById('a').disabled=false;
}else {
document.getElementById('a').disabled=true;
}
}
</script>
</body>
</html>
关于javascript - 当文本框为空时 onkeyup 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772138/