如何使用jQuery禁用表单的提交按钮,直到填写完每个必填字段为止?

如何使用jQuery禁用表单的提交按钮,直到填写完每个必填字段为止?

问题描述:

我有一个包含多个输入,选择框和一个textarea的表单。我希望禁用提交按钮,直到我指定的所有字段都填充了一个值。当它们全部填满后,如果一个字段被WAS字段删除,我想要提交按钮再次变为禁用。

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are filled with a value. And after they are all filled, should a field that WAS field get erased by the user, I would like the submit button to turn back to disabled again.

我怎么能用jQuery完成这个任务?

How can I accomplish this with jQuery?

猜猜我的第一个直觉是每当用户开始修改任何输入时运行一个函数。像这样:

Guess my first instinct would be to run a function whenever the user starts modifying any of the inputs. Something like this:

$('#submitBtn').prop('disabled', true);
$('.requiredInput').change(function() {
   inspectAllInputFields();
});

然后我们会有一个函数来检查每个输入,如果它们被验证,那么启用提交按钮...

We then would have a function that checks every input and if they're validated then enable the submit button...

function inspectAllInputFields(){
     var count = 0;
     $('.requiredInput').each(function(i){
       if( $(this).val() === '') {
           //show a warning?
           count++;
        }
        if(count == 0){
          $('#submitBtn').prop('disabled', false);
        }else {
          $('#submitBtn').prop('disabled', true);
        }

    });
}

您可能还希望在页面加载时将调用添加到检查函数这样,如果输入值被存储或者你的其他代码正在填充数据,它仍然可以正常工作。

You may also want to add a call to the inspect function on page-load that way if the input values are stored or your other code is populating the data it will still work correctly.

 inspectAllInputFields();

希望这会有所帮助,
〜Matt

Hope this helps, ~Matt