4

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 :)

3
  • 6
    An id must be unique within the document. Commented Jan 30, 2013 at 22:22
  • @David Thomas, yes id also is unique in document Commented Jan 30, 2013 at 22:27
  • Look at what I said in my previous comment, then look at your HTML. Specifically the id attribute of every input element. Commented Jan 30, 2013 at 22:29

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

6 Comments

thank you for answer but hasDups always return true, i put diffrent emails but return true, why?
Right, I forgot...change to this !values.every(function() {.... Works fine now jsbin.com/ezinad/1/edit
hmm now always return false?
yes I check the demo, I change the values for example i put two time three and console return false!
the problem is in value, when i put the value in HTML is working fine but when i put in the text field and submit value comes empty
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.