且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

禁用提交按钮,直到所有表单输入都包含数据

更新时间:2022-12-17 18:08:50

这是对代码的修改,它检查所有<input>字段,而不仅仅是第一个字段.

Here's a modification of your code that checks all the <input> fields, instead of just the first one.

$(document).ready(function() {
  validate();
  $('input').on('keyup', validate);
});

function validate() {
  var inputsWithValues = 0;
  
  // get all input fields except for type='submit'
  var myInputs = $("input:not([type='submit'])");

  myInputs.each(function(e) {
    // if it has a value, increment the counter
    if ($(this).val()) {
      inputsWithValues += 1;
    }
  });

  if (inputsWithValues == myInputs.length) {
    $("input[type=submit]").prop("disabled", false);
  } else {
    $("input[type=submit]").prop("disabled", true);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>
<input type="submit" value="Join">