Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Elegant Way See If All Input Fields Are Distinct

Tags:

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

Thanks in advance!

like image 454
Mark Hardin Avatar asked May 11 '12 14:05

Mark Hardin


3 Answers

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

If you can't use ES6 (or other modern JS features), use jQuery's 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);
});

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...

like image 67
Joseph Silber Avatar answered Sep 28 '22 16:09

Joseph Silber


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

DEMO

like image 31
ilyes kooli Avatar answered Sep 28 '22 14:09

ilyes kooli


Try adding a unique to all the classes you want to be unique, add thier values to an array, and then check to see if the array has only unique values.

<input type="text" class="unique" id="email1" />
<input type="text" class="unique" id="email2" />

Then using jQuery:

var values = $('input.unique').map(function(){
    return $(this).val();
}).get();

Then check if the array is unique:

var uniqueValues = $.grep(values, function (v, k) {
    return $.inArray(v, values) === k;
});

if(uniqueValues.length !== values.length){
    alert('emails must be unique.');
}
like image 42
Rocket Hazmat Avatar answered Sep 28 '22 14:09

Rocket Hazmat