Ranaz 116 Ranaz 116 - 13 days ago 6
HTML Question

Working with checkboxes in jQuery

I'm trying to write code that displays an

alert
when a checkbox is checked but it's not working. I have tried different code online but still can't get it to work. Could anyone please help me. Thank you.

<div id="filterBox">
<input type="checkbox" value="categorya" id="one" />
<label for="one">One </label>

<input type="checkbox" value="categorya" id="two" />
<label for="two">Two </label>

<input type="checkbox" value="categorya" id="three" />
<label for="three">Three </label>
</div>


$(document).ready(function() {
if ($('#one').is(":checked")) {
console.log("testing");
}
});

Answer

You are missing the click event. You can try as follows.

$(document).ready(function(){
  $('input[type="checkbox"]').click(function(){
    if ($('#one').is(":checked")) {
        console.log("testing");
    }
  });
});

Or you can use a change event as follows as suggested by @Rory McCrossan.

$(document).ready(function(){
  $('input[type="checkbox"]').change(function(){
    if ($('#one').is(":checked")) {
        console.log("testing");
    }
  });
});

Working JSFiddle sample is here

Comments