如果使用jQuery输入为空,则禁用提交按钮

我试图禁用提交按钮,直到用户填写表单中的输入字段。

我发现这里有一个非常好的答案。 填写字段时,重新启用提交按钮时遇到一点问题。

有人可以看看这个function,帮我弄清楚我错过了什么? 任何帮助将不胜感激:D谢谢。

还有一个小提琴

$(document).ready(function() { var $submit = $("input[type=submit]"); if ( $("input:empty").length > 0 ) { $submit.attr("disabled","disabled"); } else { $submit.removeAttr("disabled"); } }); <form method="POST" action=""> User Name: 
Password:

 $(document).ready(function() { var $submit = $("input[type=submit]"), $inputs = $('input[type=text], input[type=password]'); function checkEmpty() { // filter over the empty inputs return $inputs.filter(function() { return !$.trim(this.value); }).length === 0; } $inputs.on('blur', function() { $submit.prop("disabled", !checkEmpty()); }).blur(); // trigger an initial blur }); 

工作样本

您也可以使用如下键盘而不是模糊:

  $inputs.on('keyup', function() { $submit.prop("disabled", !checkEmpty()); }).keyup(); // trigger an initial keyup 

您还可以组合多个事件:

  $inputs.on('keyup blur', function() { $submit.prop("disabled", !checkEmpty()); }).keyup(); // trigger any one 

在你的问题中,我没有看到代码,你不断检查输入的状态,我认为问题是。

您可以使用直播活动来完成此操作。 以您的代码为例:

 $(document).ready(function() { var $submit = $("input[type=submit]"); function checkSubmitState() { if ( $("input:empty").length > 0 ) { $submit.attr("disabled","disabled"); } else { $submit.removeAttr("disabled"); } } // check the submit state on every change or blur event. $("input").live("change blur", checkSubmitState); }); 

在运行条件之前使用keyup事件检查值:

 $(document).ready(function() { $('input:text, input:password').keyup(function() { if ($(this).val() !== "") { $('input:submit').removeAttr('disabled'); } else { $('input:submit').attr('disabled', 'true'); } }); }); 

http://jsfiddle.net/tovic/He4Kv/23/

由于我正在寻找一个jQuery片段,因此这里的一些答案已经过时了。 我测试了它们,由于我认为已经弃用,它们似乎不再正常运行。

所以我自己做了,这是一个更新的工作方式(jQuery> = 3.0),例如,它监听输入事件。

 let inp = $('[type=text]'), btn = $('[type=button]') btn.prop('disabled', true) inp.on('input', () => { let empty = [] inp.map(v => empty.push(inp.eq(v).val())) btn.prop('disabled', empty.includes('')) })