如果输入为空jquery,则禁用提交

免责声明:我知道有很多关于这个主题的问题并且已经得到了很好的解决,尽管在我的特定情况下我需要帮助。

我试图检查密钥上的输入值是否为空,然后禁用提交按钮。

我的HTML代码段:

我从这里使用了示例答案并进行了一些修改:

 (function() { $('.field input').keyup(function() { var empty = false; $('.field input').each(function() { if ($(this).val() == '') { empty = true; } }); if (empty) { $('.actions input').attr('disabled', true); } else { $('.actions input').attr('disabled', false); } }); })() 

任何帮助将不胜感激!

我建议默认禁用该按钮。 我还会查看.val()的长度,而不是检查空字符串。 最后,我认为document.ready()比现有代码更具可读性:以下是完整代码:

HTML

 

JS / jQuery的

 $(document).ready(function() { $('.field input').keyup(function() { var empty = false; $('.field input').each(function() { if ($(this).val().length == 0) { empty = true; } }); if (empty) { $('.actions input').attr('disabled', 'disabled'); } else { $('.actions input').removeAttr('disabled'); } }); }); 

这是一个工作小提琴 。

我在我的项目中使用它并取得了成功。

 $(document).ready(function() { $('.field').keyup(function() { var empty = false; $('.field').each(function() { if ($(this).val().length == 0) { empty = true; } }); if (empty) { $('.actions[type="submit"]').attr('disabled', 'disabled'); } else { $('.actions[type="submit"]').removeAttr('disabled'); } }); }); 

您可以像这样编写它而不是使用“if”条件

 $('button[type=submit]').prop('disabled', empty);