Wicker
Wicker

Reputation: 1

Check and un-check checkboxes using Javascript

Hey guys im trying to get a checkbox scenario worked out, I have 7 boxes and im trying to get a logic statement where it works things out. I have 7 checkboxes and the 7th box is all of the above, when all of the above is clicked it deselects all of the previous ones, when 1-6 is selected it deselects the all of the above box. What ends up happening in my current code it deselects all of the 1-6 boxes and then they are now unable to click. Unfortunately i'm kind of constrained to things. so i'll paste my code any help greatly appreciated.

This is a snippet of very horrible coding, i just through this together while i was trying multiple ways to get it to work.

if (document.forms[0].propDetails[6].checked==true) {
for (var x=0;x<6;x++) {
document.forms[0].propDetails[x].checked=false;
}
}
else {
document.forms[0].propDetails[6].checked=false;
}
} // end of function

Upvotes: 0

Views: 741

Answers (2)

dominicbri7
dominicbri7

Reputation: 2599

I first suggest that you give a specific NAME attribute to the 1-6 checkboxes, and parsing them using getElementsByName like so :

<input type="checkbox" id="myChk1" name="myChk" />
...
<input type="checkbox" id="myChk6" name="myChk" />

<input type="checkbox" id="myChkAll" onchange="chkAll(this);" />

<script type="text/javascript">
function chkAll(obj) {
    var isChecked = obj.checked;

    var chk1to6 = document.getElementsByName('myChk');

    for (var i = 0 ; i < chk1to6.length ; i++) {
        chk1to6[i].checked = isChecked;
    }
}
</script>

Upvotes: 1

Sangeet Menon
Sangeet Menon

Reputation: 9915

Give different unique Id to all the checkboxs... like

  • chckbx1

  • chckbx2

  • chckbx3

    .

    .

  • chckbx7

the call a same function on click of any of the checkbox with the object of that checkbox

i.e. onclick=functionname(this);

In side the function check the id

functioname(str){
if(str.id=="chckbx7"){
//deselect all except chckbx7
}
else{
//deselect chckbx7
}
}

Upvotes: 0

Related Questions