pixie123 pixie123 - 8 days ago 4x
CSS Question

JavaScript cannot check checkbox

This is my code: https://jsfiddle.net/56xh3rLo/

Here is the javascript from the jsfiddle:

$(document).ready(function() {
$(document).click(function(event) { //line 1
if(!$(event.target).closest('.menu').length) { //line 2
if ($('.menu-btn').is(':checked')) { //line 3
$('.menu-btn').trigger('click'); //line 4

as you can see, line 1 is to detect if a user is going to click on the page. line 2 is to detect if the user clicks on anywhere EXCEPT for the .menu element (which is anywhere in the black background). Line 3 is to detect if the .menu-btn checkbox is checked. if it is checked, it will trigger a click on the checkbox.

So, here is the summary of the code: if the user clicks on anywhere EXCEPT for the black box area and the checkbox IS checked, the code will trigger a click on the checkbox and it will uncheck the checkbox. the problem is, the checkbox does not even check at all. why is it not working?


You want to change your outer if check to

if(!$(event.target).closest('.menu').length && !$(event.target).hasClass('menu-btn')) {

The way you're doing it now is seeing if the click target has an ancestor with the .menu class, but if you click the checkbox, it will not have that ancestor. This means the outer if check will pass, then the inner if check will pass because the click you just did checked the box. That will run the line

$('.menu-btn').prop( "checked", false );

Here's the working example.