Hi, I've got a table with 3 cols and each cell has a checkbox. I want to have 3 checkboxes above the table that each one checks/unchecks all the checkboxes in the table but ONLY in one col. so if I click checkbox 1 all the checkboxes in col 1 are checked, if I click checkbox 2 all the checkboxes in col 2 are checked, etc..

I found this code that checks all the checkboxes in 1 <form>, using the form's ID attribute.
but my table is in 1 form, I can't separate it into 3 forms and I can't give the checkboxes in the table different ID or NAME...

I tried to give the table's <td> different ID and using it in the JS function instead of the <form>'s ID but it doesn't work...

here's the code-

<script language='JavaScript'>
      checked = false;
      function checkedAll () {
        if (checked == false){checked = true}else{checked = false}
	for (var i = 0; i < document.getElementById('myform').elements.length; i++) {
	  document.getElementById('myform').elements[i].checked = checked;
	}
      }
    </script>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="myform">
   
    Check col1: <input type='checkbox' name='checkall' onclick='checkedAll();'>
   <!-- Check col2: <input type='checkbox' name='checkall' onclick='checkedAll();'>
    Check col3: <input type='checkbox' name='checkall' onclick='checkedAll();'>-->

<table width=100%>	
  <tr class=trHead>
	<td>  1</td>
	<td>  2</td>
	<td>  3</td>
  </tr>
//start of a loop
  <tr>
     <td><input type="checkbox" name="checkbox[]" id="checkbox[]"  value="dfg"/>dfg</td>
     <td><input type="checkbox" name="checkbox[]" id="checkbox[]"  value="dfg"/>df</td>
     <td><input type="checkbox" name="checkbox[]" id="checkbox[]"  value="sd"/>sd</td>
  </tr>
//end of a loop
</table>
</form>

Dani AI

Generated

A compact, robust way to toggle a single table column without changing input names is to target the checkbox inputs by their table-cell position (CSS nth-child or row.cells). This avoids relying on duplicate IDs or changing the server-side name checkbox[] (which is fine for PHP). 's jQuery/data-attribute idea is solid if jQuery is acceptable; below is a plain‑JavaScript alternative that works in modern browsers and leaves the inputs' names intact.

document.addEventListener('DOMContentLoaded', function () {
  function toggleColumn(colIndex, checked) {
    var selector = '#myTable tr td:nth-child(' + colIndex + ') input[type="checkbox"]';
    var boxes = document.querySelectorAll(selector);
    for (var i = 0; i < boxes.length; i++) boxes[i].checked = checked;
  }

  var headerToggles = document.querySelectorAll('.colToggle');
  for (var i = 0; i < headerToggles.length; i++) {
    (function(btn){
      btn.addEventListener('change', function () {
        var idx = parseInt(btn.getAttribute('data-col'), 10); // 1-based
        toggleColumn(idx, btn.checked);
      });
    })(headerToggles[i]);
  }
});

Notes and troubleshooting:

  • nth-child is 1-based; data-col should match the visual column (1,2,3). If the table uses colspan/rowspan or has mixed cell structure, switch to per-row cell access (row.cells[colIndex-1]) to find the checkbox inside that cell.
  • Duplicate id values in the page are invalid HTML and can cause surprises; the script above avoids getElementById for that reason. If possible, remove duplicate ids from inputs even while keeping the name="checkbox[]".
  • To keep header checkboxes in sync (indeterminate/checked) when individual boxes are toggled, add a change listener to the table's checkboxes that recomputes whether all/none are checked for that column and updates the corresponding header .colToggle.
  • If the table is modified dynamically (rows added/removed), either re-run the header wiring or delegate/snapshot as rows change.

This approach solves the original constraint from (single form, same input names) while giving predictable column toggling without restructuring the form.

Recommended Answers

All 2 Replies

Member Avatar for Member #905211

First, get rid of the [] in the name and id, they are pointless and can confuse people into thinking they are an array when they are not.

Secondly, I'd use jQuery for this as it would make it a lot easier to accomplish what you want.

Here is a complete example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Fun Little Widget</title>

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

<script>

$(function(){
	$('#firstRowCheckAll').click(function(){
		if($(this).is(':checked')){
			$('[data-column="1"]').attr('checked', 'checked');
		}
		else{
			$('[data-column="1"]').removeAttr('checked');
		}
	});

	$('#secondRowCheckAll').click(function(){
			if($(this).is(':checked')){
				$('[data-column="2"]').attr('checked', 'checked');
			}
			else{
				$('[data-column="2"]').removeAttr('checked');
			}
	});

	$('#thirdRowCheckAll').click(function(){
			if($(this).is(':checked')){
				$('[data-column="3"]').attr('checked', 'checked');
			}
			else{
				$('[data-column="3"]').removeAttr('checked');
			}
	});
});

</script>

</head>
<body>

<table>
	<tr>
		<td>
		Check all:<input id="firstRowCheckAll" type="checkbox" />
		</td>
		<td>
		Check all:<input id="secondRowCheckAll" type="checkbox" />
		</td>
		<td>
		Check all:<input id="thirdRowCheckAll" type="checkbox" />
		</td>
	</tr>
	<tr>
		<td>
		<input data-column="1" type="checkbox" />
		</td>
		<td>
		<input data-column="2" type="checkbox" />
		</td>
		<td>
		<input data-column="3" type="checkbox" />
		</td>
	</tr>
	<tr>
		<td>
		<input data-column="1" type="checkbox" />
		</td>
		<td>
		<input data-column="2" type="checkbox" />
		</td>
		<td>
		<input data-column="3" type="checkbox" />
		</td>
	</tr>
	<tr>
		<td>
		<input data-column="1" type="checkbox" />
		</td>
		<td>
		<input data-column="2" type="checkbox" />
		</td>
		<td>
		<input data-column="3" type="checkbox" />
		</td>
	</tr>
	<tr>
		<td>
		<input data-column="1" type="checkbox" />
		</td>
		<td>
		<input data-column="2" type="checkbox" />
		</td>
		<td>
		<input data-column="3" type="checkbox" />
		</td>
	</tr>
	<tr>
		<td>
		<input data-column="1" type="checkbox" />
		</td>
		<td>
		<input data-column="2" type="checkbox" />
		</td>
		<td>
		<input data-column="3" type="checkbox" />
		</td>
	</tr>
</table>

</body>
</html>

I don't think I'll get rid of the [] I'm using it for other stuff that took me forever to make work, and [] is part of the trick...why? I have no idea..I DON'T understand the checkboxes in PHP and avoid using them whenever possible!
I hope ur code will work with the []...I'll check it out now, thank you anyways :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.