JavaScript DOM Scripting By Example Improving the Application Code Next Steps

Saqib Ishfaq
Saqib Ishfaq
13,911 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
173,958 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.