natanel97 natanel97 - 1 year ago 73
HTML Question

JavaScript - Toggle "check all" checkboxes true/false

I am trying to make "toggle checkboxes" function, as below:

HTML Code:

<!-- "Check all" box -->
<input type="checkbox" name="check" id="cbx_00_00" onclick="selectbox( this.getAttribute( 'id' ));" />
<!-- the other ones -->
<input type="checkbox" name="check" id="cbx_00_01" />
<input type="checkbox" name="check" id="cbx_00_02" />
<input type="checkbox" name="check" id="cbx_00_03" />


function selectbox( eID ) {

// instead of writing the element id in the html code,
// i want to use "this.getAttribute( 'id' )"
var c = document.getElementById( eID );

// now when we've got the id of the element,
// let's get the required attribute.
var box = c.getAttribute( 'name' );

// set var i value to 0, in order to run "for i" loop
var i = 0;

for(i; i < box.length; i++) {

// now lets find if the main box (as box[0]) checked.
// if returns true (it has been checked), then check all - else -
// do not check 'em all.
if(box[0].checked == true) {

box[i].checked = true;

else {

box[i].checked = false;




I don't want any jQuery solution (even if it can be easier than pure js), so please avoid suggesting it. All I want to know is - If I'm wrong - what do you think I should do to solve this?
Thank you very much. every suggestion/tip is appreciated.

Answer Source

Your problem mainly seems to be that you are iterating over the checkbox name, not the checkboxes with that name.

var box = c.getAttribute( 'name' );

Now, box is equal to "check", so box[0] is "c", box[1] is "h" etc.

You need to add this:

var boxes = document.getElementsByName(box);

And then iterate over boxes.

Of course, at that point, you may want to rename your variables too.