javascripthtml

How to check and uncheck all checkboxes


I have a problem with my code. I am trying to click on the button to check all of the checkboxes but nothing is working.

Here's my code.

<body>
<html>

<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer"  value="<?php echo $rowTrackers['id']; ?>" />
<br>

<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer"  value="<?php echo $rowTrackers['id']; ?>" />
<br>


<input type="checkbox" id="chk_boxes1" name="chk_boxes1" class="delete_customer"  value="<?php echo $rowTrackers['id']; ?>" />
<br>

<button type="button" name="btn_checkall" id="btn_checkall">Check all</button>

</html>
</body>


<script>
$(document).ready(function(){

 $('#btn_checkall').click(function(){
    if($(this).prop('checked')){
      $('.chk_boxes1').prop('checked', true);
    }else{
      $('.chk_boxes1').prop('checked', false);
    }
 });


});
</script>

I don't know where the trouble is coming from, but I guess that something have to do with the id, name or whatever it is that make it stop working.

Can you please show me the correct code that I could use to check and uncheck all of the checkboxes when I click on a button using with my code?


Solution

  • One thing to correct is that you have your html tag after your body tag. The html tag should for sure be the parent.

    Other than this it looks like you have assigned "chk_boxes1" to id's instead of classes. If you change them to classes then things should work:

    <input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1"  value="<?php echo $rowTrackers['id']; ?>" />
    <br>
    <input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1"  value="<?php echo $rowTrackers['id']; ?>" />
    <br>
    <input type="checkbox" name="chk_boxes1" class="delete_customer chk_boxes1"  value="<?php echo $rowTrackers['id']; ?>" />
    <br>
    

    Also you are checking at button to determine checked status. This also will make the code not work. You can add and remove a class to the button if you want to change status or you can do something like this to check the group of checkboxes:

    $(document).ready(function(){
    
     $('#btn_checkall').click(function(){
        if ($('.chk_boxes1:checked').length == $('.chk_boxes1').length) {
          $('.chk_boxes1').prop('checked', false);
        }
        else {
          $('.chk_boxes1').prop('checked', true);
        }
     });