检查是否至少有一个文本字段填充了jQuery
Check if at least one textfield is filled with jQuery
我有一个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>
相关文章:
- 单击鼠标,用MySQL数据填充html表单输入字段
- 如何用URL预填充wufoo字段
- 根据Rails4中的一个字段自动填充表单
- 在输入字段中选择一个值,然后用相应的数据填充另一个字段
- 自动填充动态字段上的 ajax 响应
- Angularjs 通过选择不同选择框中的两个字段来填充选择框
- 如何使用与单个查找字段相关的信息填充字段
- 使用 JSON 数组填充输入字段
- 动态填充字段的Jquery验证
- IE JavaScript参数和填充输入字段
- 从替代字段填充 jquery UI 日期选择器日期字段
- 基于一个输入字段填充另一个输入字段
- 翡翠选择字段填充数据
- html5输入字段填充问题
- 根据ID号字段填充性别和出生日期字段
- 量角器测试通过,但无法看到搜索字段填充
- 从多个输入字段填充字段
- Javascript:如何打开一个字段填充参数的表单
- 根据另一个字段填充输入
- 高级自定义字段/基于另一个字段填充选择