0

I am having a lot of trouble trying to select all checkboxs with a click of a button.

As I am creating a messaging system, I am using PHP while loop to generate all of the checkboxes and have no problem with that.

When I click the Check All button, it will only check the first checkbox, any other checkbox below is ignored for some reason.

The code I am using is as follows:

<button type='button' name='btn-check' id='btn-check' class='btn btn-default btn-sm' onclick='check()'>Check All</button>

<input type='checkbox' name='cb_delete[]' id='cb_delete' value='$mID'>

<script type="text/javascript">
   function check() {
     document.getElementById("cb_delete").checked = true;
     $("#btn-check").attr('disabled','disabled');
     $("#btn-uncheck").removeAttr('disabled','disabled');
     $("#btn-delete").removeAttr('disabled','disabled');
   }
</script>

I have tried changing getElementById, to getElementByType, ByName, etc and still no luck. Any help would be appreciated.

Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
James
  • 557
  • 1
  • 8
  • 22

2 Answers2

2

The reason is (most probably) that you're using the same id attribute for each checkbox.
The id attribute is meant to be an identifier and as such, must be unique in the whole document.

Try to use class instead of id:

<button type='button' name='btn-check' id='btn-check' class='btn btn-default btn-sm'>Check All</button>

<input type='checkbox' name='cb_delete[]' class='cb_delete' value='$mID'>

Script:

$("#btn-check").click(function(){
    $(this).prop('disabled', true);
    $("#btn-uncheck").removeAttr('disabled');
    $('.cb_delete').prop('checked', true);
});

On a side note - It's not a good practice to use onClick attribute

Community
  • 1
  • 1
Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
1

Working JSFiddle

Since you are using jQuery you can resolve this by replacing

document.getElementById("cb_delete").checked = true;

with

$(":checkbox").prop('checked', true);

Andrew Hill
  • 2,165
  • 1
  • 26
  • 39