Millica Millica - 2 months ago 20
HTML Question

Toggle checkboxes on PHP table

I have a table with a checkbox in the table header, which will be used to toggle all the checkboxes below it. I've add a JavaScript function to the checkbox in the header, but so far it only selects the top checkbox (one checkbox) instead of all of them. Any suggestions or advice on what I've done wrong or what to research?

HTML table header code:

<thead>
<tr>
<th><center><input type="checkbox" value="" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbgroup1')"></center></th>
<th>Sender</th>
<th>Receiver</th>
<th>Subject</th>
<th>Date</th>
</tr>
</thead>


PHP table code:

$table .= '
<tr>
<td><center><input type="checkbox" id="cb1_1" class="cbgroup1"></center></td>
<td><a href="pm_message.php?u='.$log_username.'&pmid='.$pmid.'" onclick="markRead(\''.$pmid.'\',\''.$sender.'\')">'.$sender.'</a></td>
<td>'.$receiver.'</td>
<td>'.$subject.'</td>
<td>'.$time.'</td>
</tr>';


Javascript code:

function togglecheckboxes(master,cn){
var cbarray = document.getElementsByClassName(cn);
for(var i = 0; i < cbarray.length; i++){
var cb = document.getElementById(cbarray[i].id);
cb.checked = master.checked;
}
}

Answer

I see 2 issues with you code.

(Probably) using the same id for multiple DOM elements

Your PHP code suggests that you are probably using a loop to create the checkboxes but you are using the same id for all of them "cb1_1". Same as @atul here.

Improperly selecting your checkbox elements Since you are using the same id for all inputs, var cb = document.getElementById(cbarray[i].id);always returns the same element. A way to solve it is to use the solution provided by @atul

Another way is to rewrite your javascript as follows :

function togglecheckboxes(master,cn){
    var cbarray = document.getElementsByClassName(cn);
    for(var i = 0; i < cbarray.length; i++){
        var cb = cbarray[i];
        cb.checked = master.checked;
    }
}

Your cbarray is already your checkboxes array, so it is redundant (aka useless) to call document.getElementById(cbarray[i].id) to get the element when you already have it with cbarray[i].

Comments