Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find duplicate values in array using jQuery?

Tags:

jquery

I have some inputs which names is array in one form:

<input type="text" name="email[]" id="email" />
<input type="text" name="email[]" id="email" />
<input type="text" name="email[]" id="email" />

etc.

when I submit the form I need to check in jQuery if have a duplicated value in this inputs, can help me anyone?

thanks :)

like image 238
elvaris17 Avatar asked Dec 27 '22 10:12

elvaris17


1 Answers

I'd do it like this:

var values = $('input[name="email[]"]').map(function() {
  return this.value;
}).toArray();

var hasDups = !values.every(function(v,i) {
  return values.indexOf(v) == i;
});

$('form').submit(function(e) {
   if (hasDups) e.preventDefault();
});

Also, ids should be unique like people are saying in the comments.

like image 116
elclanrs Avatar answered Jan 08 '23 10:01

elclanrs