Check/Uncheck all the checkboxes in a table
Actually your checkAll(..)
is hanging without any attachment.
1) Add onchange
event handler
<th><INPUT type="checkbox" onchange="checkAll(this)" name="chk[]" /> </th>
2) Modified the code to handle check/uncheck
function checkAll(ele) {
var checkboxes = document.getElementsByTagName('input');
if (ele.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
Updated Fiddle
This will select and deselect all checkboxes:
function checkAll()
{
var checkboxes = document.getElementsByTagName('input'), val = null;
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].type == 'checkbox')
{
if (val === null) val = checkboxes[i].checked;
checkboxes[i].checked = val;
}
}
}
Demo
Update:
You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:
function checkAll()
{
var table = document.getElementById ('dataTable');
var checkboxes = table.querySelectorAll ('input[type=checkbox]');
var val = checkboxes[0].checked;
for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
}
Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:
function checkAll (tableID)
{
var table = document.getElementById (tableID);
var val = table.rows[0].cells[0].children[0].checked;
for (var i = 1; i < table.rows.length; i++)
{
table.rows[i].cells[0].children[0].checked = val;
}
}
Demo
JSBin
Add onClick event to checkbox where you want, like below.
<input type="checkbox" onClick="selectall(this)"/>Select All<br/>
<input type="checkbox" name="foo" value="make">Make<br/>
<input type="checkbox" name="foo" value="model">Model<br/>
<input type="checkbox" name="foo" value="descr">Description<br/>
<input type="checkbox" name="foo" value="startYr">Start Year<br/>
<input type="checkbox" name="foo" value="endYr">End Year<br/>
In JavaScript you can write selectall function as
function selectall(source) {
checkboxes = document.getElementsByName('foo');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}