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 DOM Scripting By Example Improving the Application Code Next Steps

Saqib Ishfaq
Saqib Ishfaq
13,912 Points

i added alert box if input is empty string but there is a problem!! help please

did it with an "if" statement , it shows the box when click submit, but it also adds the empty invitees into the list items.

  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const text = input.value;
  input.value = '';
  if(input.value === ''){
      alert("can't leave blank,Please write a name");
  }
  const li = createLi(text);
  ul.appendChild(li);

});
Adam McGrade
Adam McGrade
26,333 Points

The issue here is that you are setting the value of input.value to an empty string before testing to see if input.value is equal to an empty string. The if statement will always be true, and therefore an alert will always be displayed. As you have set the value of input.value to an empty string, when you create the li element the value will always be empty.

You will need to use a if/else statement to check that the input.value is not empty. Then if it is not empty, append the new li element and set the input.value to an empty string.

form.addEventListener('submit', (e) => {
   e.preventDefault();
   const text = input.value;
   if (text === '') {
     alert("can't leave blank, Please write a name");
   } else {
      const li = createLi(text);
      ul.appendChild(li);
      input.value = '';
   }
}

Hope that helps.

1 Answer

Steven Parker
Steven Parker
231,236 Points

The statements outside the test are always done. But you could enclose them in a block (with braces) after an "else" statement and they would only be done when the input value is not blank.