How can I find duplicate values ​​in an array using jQuery?

I have some inputs whose names are arrays in one form:

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

      

and etc.

when i submit the form i need to validate jQuery, if you have duplicate value on these inputs can anyone help me?

thank:)

+3


source to share


1 answer


I would 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 must be unique, as people say in the comments.

+7


source







All Articles