jQuery Elegant Way查看所有输入字段是否不同 [英] jQuery Elegant Way See If All Input Fields Are Distinct

查看:65
本文介绍了jQuery Elegant Way查看所有输入字段是否不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含十几个电子邮件输入字段的表单,每封电子邮件都必须是唯一的。通过jquery在所有字段之间执行比较的最优雅方式是什么,而无需手动编写如下所示的所有比较:

I have a form with a dozen email input fields and each email needs to be unique. What is the most elegant way via jquery to perform the comparison among all the fields without manually writing all the comparisons like below:

if($("#email1").val() == $("#email2").val() || ....)  {
    isValid = false;
    alert("emails must be unique.");
}

提前致谢!

推荐答案

最简单的方法是将电子邮件放入 Set ,并比较其大小:

The simplest way is to put the emails into a Set, and compare its size:

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.');
}






如果你不能使用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);
});






如果选择器过宽,您可以指定你的ID在逗号分隔的列表中,如下所示:


If that selector is too broad, you can specify your IDs in a comma separated list, like this:

$('#email1, #email2, #email3') // ...and so on

或只是为所有人添加一个类你想要选择的元素......

or just add a class to all the elements you want to select...

这篇关于jQuery Elegant Way查看所有输入字段是否不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆