javascript - 使用退格键或删除按钮时提交按钮颜色不改变

标签 javascript jquery html css

我有一个 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/

相关文章:

javascript - 我如何在 AIR Android 应用程序中在 JS 和 AS3 之间进行通信?

javascript - 幻灯片播放 2 次循环后停止?

javascript - 如何在 JavaScript 中模拟 let 表达式?

javascript - 如何删除表单中的按钮格式以便将按钮用作切换按钮?

javascript - 使用箭头键导航多步骤表单?

html - 用于 HTML 5 视频的 MP4 持续时间的 HTTP header

javascript - 根据id标签动态添加图片

javascript - Flex (toFixed) 数字格式

javascript - slider 无法正常工作,并且出现 TypeError : jQuery(. ..).easyResponsiveTabs 不是函数

jquery - 为什么在 <li> 中具有相同高度和行高的 <a> 在 Safari 中看起来比在其他浏览器中更高,尽管使用了重置?