【问题标题】:Disable form button unless all text input fields are filled in除非填写了所有文本输入字段,否则禁用表单按钮
【发布时间】:2015-02-09 11:10:40
【问题描述】:

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

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

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

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

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

【问题讨论】:

标签: javascript jquery forms


【解决方案1】:
$('#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

【讨论】:

  • @User9876867 很高兴为您提供帮助。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    试试这个:

    $(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' />

    【讨论】:

    • 在最后一个文本框中输入文本并检查会发生什么?它启用了按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2018-01-22
    • 2019-11-22
    • 1970-01-01
    相关资源
    最近更新 更多