Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Reject name duplicates in form

Hey guys! I just want to ask how to reject name duplicates in form. I've been trying in some way but it doesn't work. Could someone help me figure out what might be the problem with the code below? I'll really appreciate it.

const ul = document.getElementById('invitedList'); const form = document.getElementById('registrar');

form.addEventListener('submit', (e) => { e.preventDefault(); const text = input.value; input.value = ''; const li = createLI(text); const list = ul.children; if (text === "") { alert("Please submit your name!"); } else { ul.appendChild(li); }

for (let i = 0; i < list.length; i += 1) { if (text === list[i].textContent) { alert("This name has already been submitted!"); } else { ul.appendChild(li); } } });

This has already been answered in the forums, but let me see if I can help.

In your code, if you console.log(list[0].textContent); you will get all the text in the ul in the first child.

Remember you don't just need to select the children of ul, you need to select the span elements of ul to get their textContent.

Second, take the ul.appendChild out of the for loop or else you would append (i - 1) children to ul.

Ok, so I got it to work with this code. I'm sure there are other ways, but this worked for me.

  formHandler.addEventListener('submit', (e) => {
    e.preventDefault();
    const text = inputData.value;
    inputData.value = "";

    const li = createLI(text);

    //this bool will turn false if the person's name is on the list already
    let addName = true;

    //now check to see if submitted name is already on list

    if (text == ""){
      alert("No name was entered.")
      }else{

        //this selects only the span elements of ul    
        const list = ul.getElementsByTagName('span');
      for (let i = 0; i < list.length; i++){
        if (list[i].textContent === text){
          alert("This person has already been invited.");
          addName = false;
          //break stops for the for loop
          break;
        };
      };
      //if addName is true append to ul
      if (addName){
            ul.appendChild(li);      
      };
      };

  });