禁用和启用复选框Javascript

时间:2013-02-18 09:48:28

标签: checkbox javascript

我有一系列的复选框:

<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>

一旦用户选择了3个复选框,是否可以在一次点击中禁用其余部分(有30个复选框 - 我可以单独执行但这看起来很痛苦)?是这样,怎么会这样做呢?此外,如果用户随后取消选中其中一个复选框,是否可以再次启用它们?

编辑:如果可能的话 - 有人可以指出我正确的方向,代码明智吗?

提前致谢,

小时。

1 个答案:

答案 0 :(得分:2)

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();
}
使用

<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>