James James - 3 months ago 8
Javascript Question

Ajax/JavaScript Select All Checkbox's with button

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;

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


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'>


    $(this).prop('disabled', true);
    $('.cb_delete').prop('checked', true);