2

I have a big html form with multiple email fields. What I want to do is make sure the user can't enter the same email in more than one field.

I have managed to detect duplication successfully by defining an array where each email value the user inputs is pushed to the array and that's where the comparison happens.

the problem happens when after detecting duplication I delete the value from the input field but the value still exists in the array so my function still returns that there is a duplicate value.

here is my function code:

var filledEmail = [];
var allEmailFields = $("form input[type='email']");

function checkIfArrayIsUnique(myArray) {
  return myArray.length === new Set(myArray).size;
}

function addToEmails() {
  allEmailFields = $("form input[type='email']");
  filledEmail = [];
  allEmailFields.each(function(){
    var currentEmail = $(this);
    currentEmail.bind('change',function() {
      console.log("email value changed");
      filledEmail.push(currentEmail.val());
      console.log(filledEmail);
      if (checkIfArrayIsUnique(filledEmail) == true) {
        console.log("emails unique")
      }
      else {
        console.log("emails not unique");
      }
    })

  });
}

Any help would be so much appreciated.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Lina Basuni
  • 77
  • 2
  • 10

1 Answers1

1

This is how you could do it:

Attach change event listeners to each of your elements and check if the entered value exists. If it does not exist add it to your filledEmail array otherwise do nothing.

You will see that if you type the same name in different input element boxes it will not be added, hence will not appear as the output in the console

var filledEmail = [];

document.querySelectorAll("input[type='email']").forEach((mailField,i) => {
  mailField.addEventListener("change", e => {
    const email = e.target.value;
    const hasMail = filledEmail.find(x => x === email);
    if (!hasMail) {
      filledEmail = filledEmail.filter((x, j)=> j!==i);
      filledEmail.push(email);
    }
    console.log('filled mails without duplicates', filledEmail)
  });
});
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
<input type="email" />
EugenSunic
  • 13,162
  • 13
  • 64
  • 86