如果 2 个或更多输入字段不为空,则触发事件

Trigger an Event if 2 or more input field are not empty

本文关键字:事件 字段 输入 如果      更新时间:2023-09-26

我有一个条件,如果两个字段不为空,它将显示按钮。我的问题是如何执行事件,因为它仅在加载或加载网站时有效。我试过使用键控

.HTML

<input type="text" id="username" required="true">
<input type="email" id="email"  required="true" >
<button type="submit" id="login">
Sign Up
</button>

.JS

$(document).ready(function() {
  if ($('#email').is(':empty') && $('#username').is(':empty')){
    $('#login').hide();
  }
  else {
    $('#login').show();
  }
});

https://jsfiddle.net/w0pohLeb/1/

您可以使用

input事件。

// Bind `input` event on both the inputs
$('#email, #username').on('input', function() {
    // toggle: If argument passed is 
    //         true:  show
    //         false: hide
    $('#login').toggle($('#email').val() && $('#username').val());
}).trigger('input'); // Trigger event to call on page load

您不能使用 .is(':empty') 来检查值是否空,它仅用于检查标签是否为空并且不包含任何子项。相反,您需要使用:

$(input).val().trim().length === 0

因此,您的代码变为:

if ($('#email').val().trim().length === 0 && $('#username').val().trim().length === 0) {

而且,您需要将其附加到更好的事件,例如,在输入keyup

最终代码

$(document).ready(function() {
  if ($('#email').val().trim().length === 0 || $('#username').val().trim().length === 0) {
    $('#login').hide();
  }
  else {
    $('#login').show();
  }
  $("#email, #username").keyup(function () {
    if ($('#email').val().trim().length === 0 && $('#username').val().trim().length === 0) {
      $('#login').hide();
    }
    else {
      $('#login').show();
    }
  });
});

试试这个,希望这有帮助..:)

$(document).ready(function() {
  $('body').on('change', 'input', validate);
  validate();
  function validate() {
    var inputLength = 0;
    $('input').each(function() {
      if ($(this).attr('type') == 'text' || $(this).attr('type') == 'email' || $(this).attr('type') == 'password') {
        $(this).val() == '' ? inputLength-- : inputLength++;
      }
    });
    inputLength >= 2 ? notEmpty() : isEmpty();
  };
  function notEmpty() {
    $('#login').show();
  }
  function isEmpty() {
    $('#login').hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="username" required="true">
<input type="email" id="email" required="true">
<button type="submit" id="login">
  Sign Up
</button>

小提琴链接 https://jsfiddle.net/j6y2d1ur/1/