检查是否至少有一个文本字段填充了jQuery

Check if at least one textfield is filled with jQuery

本文关键字:字段 填充 jQuery 文本 有一个 是否 检查      更新时间:2023-09-26

我有一个HTML表单,提交后会发出一封邮件。我已经完成了邮件发送和其他一切,然而,我有一个特定的验证策略。需要填写电话号码或电子邮件字段。这两个字段都不是强制字段,但使用jQuery,我希望至少使其中一个字段成为强制字段。未经电话或电子邮件,不得提交表格。我是jQuery的新手。我的表格如下:

 <form name="myform" id="myform" role="form" method="post" action="mail.php">
    <div class="form-group">
        <label for="Phone">Phone*:</label>
        <input type="type" class="form-control" id="Phone" placeholder="Enter Phone">
        <label for="fn">First Name*:</label>
        <input type="type" class="form-control" id="fn" placeholder="Enter First Name" required>
    </div>
    <div class="form-group">
        <label for="fn">Surname:</label>
        <input type="type" class="form-control" id="fn" placeholder="Enter Surname">
        <label for="email">Email:</label>
        <input type="email" class="form-control" id="email" placeholder="Enter email">
    </div>
    <div class="form-group">
        <button type="submit" class="btn submit pull-right">Submit</button>
    </div>
</form>

应该这样做:

//When the form is submitted...
//Might want to give it an ID so you can bind to that instead (i.e. #myform)
$("form").submit(function() {
    //If both of them are empty...
    if($("#email").val().length === 0 && $("#Phone").val().length === 0) {
        //Notify the user.
        alert("You need to enter an email or a phone number.");
        //And do not submit the form.
        event.preventDefault();
    }
    //Here you can do other stuff related to submitting the form.
});

首先,您需要设置一个变量来存储结果:

var atLeastOneFilled = false;

然后,您需要浏览您感兴趣的所有字段(在本例中为#email,#Phone):

$('#email, #Phone').each(function(index, field) { ... });

然后,我们需要检查是否填写了任何字段,因此在each()函数中(我放置了"…"的位置),我们可以编写,例如:

if($(field).val !== '')
    atLeastOneFilled = true;

这样,如果至少有一个字段的值不同于"(无),则LeastOneFilled的标志将更改为true。

然后,你可以用你的变量做任何你想做的事:

if(atLeastOneFilled) {
    doSomething();
}

您可以使用filter:

$(function () {
  $("form").submit(function () {
    if ($("input").filter(function () {
      return $(this).val().trim().length > 0;
    }).length == 0)
      return false;
  });
});

下面的条件将检查任何值是否为真

if($('#email').val() || $('#Phone').val()){
   //do your actions here.
}
<script>
$( "#form" ).validate({
  rules: {
    phone: {
      require_from_group: [1, ".form-group"]
    },
    email: {
      require_from_group: [1, ".form-group"]
    }
  }
});
</script>