提问者:小点点

如果所有的输入都不需要填写,如何禁用按钮?


我必须在我的表单中禁用按钮,但不是所有的输入都是必需的。在我的代码中,我已经写好了哪些输入需要填充,但仍然必须在表单中填充所有的输入。我该怎么改变呢?

null

$('#billing_first_name, #billing_last_name, #billing_address_1, #billing_postcode, #billing_city, #billing_phone, #billing_email').bind('keyup', function dataFilled() {
  $('form > input').keyup(function() {
    var empty = false;
    $('form > input').each(function() {
      if ($(this).val() == '') {
        empty = true;
      }
    });

    if (empty) {
      $('#place_order').attr('disabled', 'disabled');
    } else {
      $('#place_order').removeAttr('disabled');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  Name<br>
  <input type="text" id="billing_first_name" name="billing_first_name"><br> Surname<br>
  <input type="text" id="billing_last_name" name="billing_last_name"><br> Company's Name (optional)<br>
  <input type="text" id="billing_company" name="billing_company"><br> Street<br />
  <input type="text" id="billing_address_1" name="billing_address_1"><br> Postal code<br>
  <input type="text" id="billing_postcode" name="billing_postcode"><br> City<br>
  <input type="text" id="billing_city" name="billing_city"><br> Phone<br>
  <input type="text" id="billing_phone" name="billing_phone"><br> E-mail<br>
  <input type="text" id="billing_email" name="billing_email"><br>
  <button type="submit" name="place_order" id="place_order" value="Buy" disabled="disabled">Buy</button>
</form>

null


共1个答案

匿名用户

有更好的方法来处理这个问题,但只要对现有代码做最小的更改,就可以预先存储输入:

var requiredFields = $('#billing_first_name, #billing_last_name, #billing_address_1, #billing_postcode, #billing_city, #billing_phone, #billing_email');
requiredFields.on('input', function () {
    var empty = false;
    requiredFields.each(function() {
      if ($(this).val() == '') {
        empty = true;
      }
    });

    if (empty) {
      $('#place_order').attr('disabled', 'disabled');
    } else {
      $('#place_order').removeAttr('disabled');
    }
});

我还删除了会多次添加的内部事件

另一种方法是给您需要的输入一个特定的类,然后使用它,例如:

$('.required').on('input', function () {
    var empty = false;
    $('.required').each(function() {
      if ($(this).val() == '') {
        empty = true;
      }
    });

    if (empty) {
      $('#place_order').attr('disabled', 'disabled');
    } else {
      $('#place_order').removeAttr('disabled');
    }
});
<input type="text" class="required" id="billing_first_name" name="billing_first_name">