James James - 1 year ago 69
HTML Question

Select All Checkboxs 'when clicking on a 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
, to
, etc and still no luck. Any help would be appreciated.

Answer Source

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);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download