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 Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perfect

How do I prevent an empty list item from being appended to the list?

Workspace snapshot: https://w.trhou.se/8w7i1rnbmc

2 Answers

You would need to add a conditional IF statement to check whether the taskInput value is an empty string. If so, it does nothing if there is text then it will render the text and add the task. Like below

//Add a new task
var addTask = function() {
  //Create a new list item with the text from #new-task:
  var listItem = createNewTaskElement(taskInput.value);
  console.log("Add task...");

  if(taskInput.value !== "") {
    //Append listItem to incompleteTasksHolder
    incompleteTasksHolder.appendChild(listItem);
    bindTaskEvents(listItem, taskCompleted);
    taskInput.value = "";
  }
}

Thanks! That worked perfectly. Appreciate your help.

Glad i could help!

Drew Cook
Drew Cook
14,612 Points

I was looking at this problem and my initial thinking was to check to see if the text field value is an empty string, and if it is, disable the button. If not, append to the list.

something like

if (taskInput.value == "") { addButton.disabled = true; } else { addButton.disabled = false; var listItem = createNewTaskElement(taskInput.value); incompleteTasksHolder.appendChild(listItem); bindTaskEvents(listItem, taskCompleted); taskInput.value = ""; }

But this was not seeming to work. I would agree that the original answer here is probably the most efficient though.