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

Zachary Baker
PLUS
Zachary Baker
Courses Plus Student 11,504 Points

How do you prevent an empty input field being added to my Todo list?

I have a todo list, most of it is done. The only bug that I have found is that you can add an empty input field to the list. How does one go about preventing that? I know it's a conditional, but I'm not sure as to the syntax that is required. Can anyone help point me in a direction so I can figure this out?

Here is a snapshot of my workspace: https://w.trhou.se/g3w3ea3nru

1 Answer

andren
andren
28,558 Points

The simplest way would probably be to add an if statement like this to the beginning of your addTask function:

if(taskInput.value.trim() === "") {
    return;
}

The trim method removes whitespace (spaces, tabs, etc) from the beginning and end of a string, so in essence if you had a string of nothing but spaces it would turn it into an empty string. The trimmed string is compared to an empty string, if it is equal to it then the function returns. In this case I'm not using return to pass a value back like you might be used to seeing return used, but instead using it as a way to exit from the function early.

With the above if statement in place if you enter nothing or just enter some spaces or something then your function will not actually add any item to the list.