我有一个包含十几个电子邮件输入字段的表单,每封电子邮件都必须是唯一的.通过jquery在所有字段之间执行比较而不手动编写如下所有比较的最优雅方式是什么:
if($("#email1").val() == $("#email2").val() || ....) {
isValid = false;
alert("emails must be unique.");
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
最简单的方法是将电子邮件放入a中Set,并比较其大小:
const $inputs = $('input[id^=email]');
const uniques = new Set($input.map((i, el) => el.value).get());
if (uniques.size < $inputs.length) {
alert('Emails must be unique.');
}
Run Code Online (Sandbox Code Playgroud)
如果您不能使用ES6(或其他现代JS功能),请使用jQuery的inArray:
var values = [];
$('input[id^=email]').each(function () {
if ($.inArray(this.value, values) >= 0) {
alert('Emails must be unique.');
return false; // <-- stops the loop
}
values.push(this.value);
});
Run Code Online (Sandbox Code Playgroud)
如果该选择器过于宽泛,您可以在逗号分隔的列表中指定您的ID,如下所示:
$('#email1, #email2, #email3') // ...and so on
Run Code Online (Sandbox Code Playgroud)
或者只是为要选择的所有元素添加一个类......
var duplicate=false;
$('input[id^=email]').each(function(){
var $this = $(this);
if ($this.val()===''){ return;}
$('input[id^=email]').not($this).each(function(){
if ( $(this).val()==$this.val()) {duplicate=true;}
});
});
if(duplicate) alert('email must be valid');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3717 次 |
| 最近记录: |