views:

56

answers:

2

Hi,

I have the following problem.

The following is the form i have

<input type="text" name="email1" />
<input type="text" name="email2" />
<input type="text" name="email3" />
<input type="text" name="email4" />
<input type="text" name="email5" />

I want all the 5 Email ids to be different (unique) i.e, i dont want the user to be entering the same Email IDs in all the fields.

I need this to be done in Javscript

Can someone please help me with this

Thanks,
Kartik

A: 
for (var i = 1; i < 6; i++) {
    for (var j = i+1; j < 6; j++) {
        if (document.getElementsByName("email"+i)[0].value ==
            document.getElementsByName("email"+j)[0].value) {
            alert("Fields "+i+" and "+j+" are equal!");
        }
    }
}

You may want to add another check, if you allow several of the fields to stay empty.

Boldewyn
+1  A: 

In Javascript an Array can act as a stack (push/pop) in which you can push new items after checking they're not already in the stack.

var emailAddrs = [];
var item;

    for(var i = 0; i < 5; i++){
      item = document.getElementsByName("email"+i)[0].value;
      if(! emailAddrs.contains(item))
        emailAddrs.push(item);
    }

UPDATE

Once you have your array build, you can then use that as a basis to do other operations. Using the length property of the array, you can check how many items are in the array vs how many you expected to see.

You could also push identical items into another array and use this information to let the user know what needs changing

UPDATE 2

I just realised that the contains method I use is created by adding the following code:

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

This then creates a contains method to each array object.

If you're using jQuery, you can also do $.inArray(value, array)

Jamie Dixon
Is there something missing from the code above? Like... you then check the size of the array and if it is 5 then all values were different?
dpb
Pretty much. Once you know how many items are in the array, and how many you expected, you can do something with that information. You can also push the identical email addresses onto anothre stack and use that information to tell the user what was identical.
Jamie Dixon
What is this magical `contains` method?
Justin Johnson
Thanks Justin. I'd got so used to using it that I'd forgotten it wasn't a native method. I've updated my answer with the relevant code.
Jamie Dixon