Search code examples
javascriptjquerycheckboxprop

Why are the checkboxes not being checked by jquery


here is the html:

<input id="globalchecker" type="checkbox"/>

<input type="checkbox" class="childcheckboxes" />
<input type="checkbox" class="childcheckboxes" />
<input type="checkbox" class="childcheckboxes" />
<input type="checkbox" class="childcheckboxes" />

and here is the jquery:

$('#globalchecker').on('click', function () {
    if($('#globalchecker').is(":checked")){
        $('.childcheckboxes:checkbox').prop('checked',true);
    }
    else{
        $('.childcheckboxes:checkbox').prop('checked', false);
    }
});

when clicking the '#globalchecker' checkbox, the '.childcheckboxes' don't get checked/un-checked. What am I doing wrong?


Solution

  • $('#globalchecker').on('change', function() { //use change
    
      $('.childcheckboxes:checkbox').prop('checked', $(this).is(":checked")); //use the state of #globalchecker as parameter for checked or not to make it 1 liner
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="globalchecker" type="checkbox" />
    
    <input type="checkbox" class="childcheckboxes" />
    <input type="checkbox" class="childcheckboxes" />
    <input type="checkbox" class="childcheckboxes" />
    <input type="checkbox" class="childcheckboxes" />

    1. Use change event