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

时间:2015-02-09 11:10:40

标签: javascript jquery forms

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

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

    <script>
        $(function () {
            $('#button').attr('disabled', true);

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

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

3 个答案:

答案 0 :(得分:6)

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

<强> Demo

答案 1 :(得分:1)

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;
}

答案 2 :(得分:1)

试试这个:

$(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
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='button' id='button' value='button' />