除非填写所有文本输入字段,否则禁用表单按钮

我有一个具有多个文本输入的表单,我不想为每个添加id,因为它们是从服务器端代码生成的 – 字段数可能不同等等。我只是希望能够禁用提交按钮,直到那里是输入到每个文本输入的文本。

我已经做到这一点,但只禁用按钮,直到文本输入到一个文本输入字段 – 我希望它保持禁用状态,直到文本输入到所有文本输入。

 $(function () { $('#button').attr('disabled', true); $('input:text').keyup(function () { $('#button').prop('disabled', this.value == "" ? true : false); }) });  

我也尝试了$('input:text').each().keyup(function (){ – 但是没有使按钮可点击?

 $('#button').attr('disabled', true); $('input:text').keyup(function () { var disable = false; $('input:text').each(function(){ if($(this).val()==""){ disable = true; } }); $('#button').prop('disabled', disable); }); 

演示

keyup的回调函数现在只检查特定输入字段的值( this.value )。 相反,这需要循环遍历所有需要填充的输入字段,并且只有当所有输入字段都有文本时才更改.prop值。

 $('input:text').keyup(function () { $('#button').prop('disabled', allFieldsAreFilled()); }); function allFieldsAreFilled() { var allFilled = true; // check all input text fields $("#yourForm input:text"]).each(function () { // if one of them is emptyish allFilled is no longer true if ($(this).val() == "") { allFilled = false; } }); return allFilled; } 

试试这个:

 $(function() { var bool = true, flag = false; $('#button').prop('disabled', bool); // use prop to disable the button $(document).keyup(function() { // listen the keyup on the document or you can change to form in case if you have or you can try the closest div which contains the text inputs $('input:text').each(function() { // loop through each text inputs bool = $.trim(this.value) === "" ? true : false; // update the var bool with boolean values if(bool) return flag; }); $('#button').prop('disabled', bool); // and apply the boolean here to enable }); });