James James - 4 months ago 14
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;
$("#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.

Answer

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