Homer_J
Homer_J

Reputation: 3323

Disable and Enable Checkboxes Javascript

I have a series of Checkboxes:

<tr id="tr5" onmouseover="changeBackgroundColor(this.id)" onmouseout="changeBackgroundColor2(this.id)">
<td class="td5"><input  name="benefit" value="Bonuses" id="benefit5" type="checkbox" onchange='addition();'</td>
<td class="td5"><label for="benefit5"> <b>Bonuses</b></label></td>

<tr id="tr6" onmouseover="changeBackgroundColor(this.id)" onmouseout="changeBackgroundColor2(this.id)">
<td class="td6"><input  name="benefit" value="Final salary pension" id="benefit6" type="checkbox" onchange='addition();'</td>
<td class="td6"><label for="benefit6"> <b>Final salary pension</b></label></td>

Once a user has selected 3 checkboxes, is it possible to disable the rest in one hit (there are 30 checkboxes - I could do it individually but that seems a pain)? Is so, how would one go about doing that? Also, if the user then un-selected one of the check boxes, is it possible to enable them again?

EDIT: If possible - could someone point me in the right direction, code wise please?

Thanks in advance,

H.

Upvotes: 1

Views: 469

Answers (1)

mplungjan
mplungjan

Reputation: 177684

DEMO

var chk=0;
function checkCheckboxes() {
  var checkboxes = document.getElementsByName("benefit");
  for (var i=0;i<checkboxes.length;i++) {
    chk += checkboxes[i].checked?1:0; // count in case we reload
    checkboxes[i].onclick=function() { // set up event handler for each
      chk+=this.checked?1:-1; // add or subtract one
      if (chk > 3) {
        console.log(chk,"too many") 
        this.checked=false;
        chk--; // we counted too many
      }
    }
  }
}


function changeBackgroundColor(row,on) {
  var id = row.id; // if you need that
  row.style.backgroundColor=(on)?"red":"white";
}
window.onload=function() {
    var trs = document.getElementById("table1").rows;
    for (var i=0;i<trs.length;i++) {
      trs[i].onmouseover=function() {
        changeBackgroundColor(this,1);
      }
      trs[i].onmouseout=function() {
        changeBackgroundColor(this,0);
      }
    }
    checkCheckboxes();
}

using

<table id="table1">
<tr id="tr1">
<td class="td1"><input  name="benefit" value="Bonuses" id="benefit1" type="checkbox"</td>
<td class="td1"><label for="benefit1"> <b>Bonuses</b></label></td>
</tr>
    <tr id="tr2">
<td class="td2"><input  name="benefit" value="Bonuses" id="benefit2" type="checkbox"</td>
<td class="td2"><label for="benefit2"> <b>Bonuses</b></label></td>
</tr>
    <tr id="tr3">
<td class="td3"><input  name="benefit" value="Bonuses" id="benefit3" type="checkbox"</td>
<td class="td3"><label for="benefit3"> <b>Bonuses</b></label></td>
</tr>
    <tr id="tr4">
<td class="td4"><input  name="benefit" value="Bonuses" id="benefit4" type="checkbox"</td>
<td class="td4"><label for="benefit4"> <b>Bonuses</b></label></td>
</tr>
        </table>

Upvotes: 2

Related Questions