Elegant jQuery path See if all input fields are great

I have a form with a dozen email input fields, and each email should be unique. What is the most elegant way through jquery to perform a comparison between all fields without manually recording all the comparisons, as shown below:

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

Thanks in advance!

+4
source share
4 answers

The easiest way is to put emails in 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 cannot use ES6 (or other modern JS functions), use 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); }); 

If this selector is too wide, you can specify your identifiers in a comma-separated list, for example:

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

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

+6
source
 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

+3
source

Try adding unique to all classes that you want to be unique, add them to the array, and then check 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.'); } 
+1
source

If you do not need exactly 12 emails, you can simply use this> smart simple JS snippet to throw out duplicates.

0
source

Source: https://habr.com/ru/post/1412012/


All Articles