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 jQuery Basics Working with jQuery Collections Stopping the Browser's Default Behavior

The :checkbox If statement

Was thinking about the condition of the 'if' statement in this video that Treasure uses which was...

if ($(':checked').length === 0) { event.preventDefault(); alert('please check the box!') }

Rather than comparing :checked.length to 0, would there be a way of comparing the value of the checkbox instead? as in something like....

if ($(':checked').val() === 'false')....... ??

Was thinking this would be more reliable than comparing the length of 2 arrays?

Thanks for any feedback!

1 Answer

Steven Parker
Steven Parker
231,275 Points

I don't know what you mean by "2 arrays", but the original test determines if there are no checked elements on the page. And in that state, the result of "val" on the empty list would be undefined, not 'false'.

The method shown is perfectly reliable when there is only one checkbox on the page. But to improve it to work even if there are others (in various checked states), I might do something like this:

if (!$(event.target).prop("checked"))   // test if this specific element is not checked

Oh so checkboxes don't have values!? So when a checkbox is 'checked' it's property changes to 'checked' rather than it's value changing to true?

Thanks again Steven

Steven Parker
Steven Parker
231,275 Points

The checkbox has a property named "checked" that will be either true or false. That's what my sample code is testing.