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 trialHosung Kim
11,243 PointsTrouble with duplicates
I can't seem to get this function to work. The function is supposed to loop through the LI in the UL and check the text input to the text content of the span element of each LI. Then if a duplicate is found: an alert window gets triggered.
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value;
checkDuplicates();
if (text === '') {
alert('Please enter a name');
} else {
input.value = '';
const li = createLI(text);
ul.appendChild(li);
}
});
function checkDuplicates () {
let text = input.value;
let ul = document.getElementById('invitedList');
let li = ul.children;
for (let i = 0; i < ul.length; i++) {
let names = li[i].firstElementChild.textContent;
if (text === names) {
alert('That person already exists in the database. Please try another name.');
}
}
}
1 Answer
Cameron Childres
11,820 PointsHi Hosung,
The problem is in your condition of the for loop:
let ul = document.getElementById('invitedList');
let li = ul.children;
for (let i = 0; i < ul.length; i++)
The variable ul does not have a length since it is simply the ul element, so the loop never runs. If you change this to li.length you'll be accessing the list of ul's children which will allow the loop to run.
With the loop running you'll notice that the alert box pops up but the name still gets added. One possible way to stop that behavior would be to include checkDuplicates() in your if/else logic:
form.addEventListener('submit', (e) => {
e.preventDefault();
const text = input.value;
if (checkDuplicates() === true) {
alert('That person already exists in the database. Please try another name.');
} else if (text === '') {
alert('Please enter a name');
} else {
input.value = '';
const li = createLI(text);
ul.appendChild(li);
}
});
function checkDuplicates () {
let text = input.value;
let ul = document.getElementById('invitedList');
let li = ul.children;
for (let i = 0; i < li.length; i++) {
let names = li[i].firstElementChild.textContent;
if (text === names) {
return true;
} else {
return false;
}
}
}
Hosung Kim
11,243 PointsHosung Kim
11,243 PointsMan...I facepalmed so hard like, "Of course!" I reread that block of code so many times over and I swore it was correct lol. Thank you, Cameron!