JavaScript jQuery Basics Working with jQuery Collections Stopping the Browser's Default Behavior

Ashley Campbell
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ashley Campbell
Front End Web Development Techdegree Graduate 19,683 Points

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
203,990 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
Ashley Campbell
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ashley Campbell
Front End Web Development Techdegree Graduate 19,683 Points

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
203,990 Points

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