我有一个 HTML 表单,当输入值小于 10 时,提交按钮将被禁用。当输入值大于 10 时,按钮会更改其颜色。
当我使用退格键或删除按钮删除输入值时出现问题,提交按钮颜色不会更改为禁用按钮,直到刷新页面。
setInterval(function () {
if ($('#tot2').val() >= 10){
$("#submit").removeAttr("disabled");
$("#submit").css({"background-color": "blue", "color": "white"});
} else {
$("#submit").attr("disabled", "disabled");
}
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="add_form" action="ebill.php" method="post" >
<input type="text" name="balance" id="tot2" value="" />
<input type="submit" id="submit" name="submit" disabled="disabled" />
</form>
最佳答案
一旦值达到 10,您就可以更改颜色,但您永远不会将它们更改回来。您可以将它们设置为空字符串 (""
),以恢复设置之前的原始颜色。 (参见jQuery - remove style added with .css() function)。
修复了以下代码:
setInterval(function () {
if ($('#tot2').val() >= 10){
$("#submit").removeAttr("disabled");
$("#submit").css({"background-color": "blue", "color": "white"});
} else {
$("#submit").attr("disabled", "disabled");
// Remove the custom colors we added.
$('#submit').css({"background-color": "", "color": ""});
}
}, 10);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="add_form" action="ebill.php" method="post" >
<input type="text" name="balance" id="tot2" value="" />
<input type="submit" id="submit" name="submit" disabled="disabled" />
</form>
(请注意,正如其他人指出的那样,最好监视输入
的更改,而不是使用计时器。)
关于javascript - 使用退格键或删除按钮时提交按钮颜色不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47009048/