PHP复选框不会撤消禁用属性,但会取消选中

时间:2013-07-31 09:09:40

标签: checkbox javascript

我有几页长代码,但是我很难让它工作。以下脚本检查all并使用onclick命令在一个主复选框上禁用具有特定ID的所有复选框。当用户取消选中该框时,复选标记将消失,但仍保持禁用状态。即使他们按下重置按钮,残疾人的盒子也会停留。

使用Javascript:

 <script>
 function checkAllbase(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].id == '1') {
      cbs[i].checked = bx.checked;
      cbs[i].disabled=true;
    }
  }
}
 </script> 

2 个答案:

答案 0 :(得分:0)

元素保持disabled,因为设置的值是常量(文字)true

您可以做的就是复制bx.disabled,就像您使用bx.checked一样:

cbs[i].checked = bx.checked;
cbs[i].disabled = bx.disabled;

或添加另一个参数以传递所需的disabled状态:

function checkAllbase(bx, disabled) {
  disabled = disabled !== false; // limit to `true` or `false`, prefer `true`
  // ...
    cbs[i].checked = bx.checked;
    cbs[i].disabled = disabled;
  // ...
}

// usage
checkAllbase(bx);        // disables elements
checkAllbase(bx, true);  // also disables elements
checkAllbase(bx, false); // enabled elements

答案 1 :(得分:0)

为每个与包关联的复选框输入提供类似的名称或类。没有看到你的实际html,提供下面的样本html

HTML

<input type="checkbox" class="package1" name="package1[]" value="vacation">
<input type="checkbox" class="package1" name="package1[]" value="bonus">
<input type="checkbox" class="package1" name="package1[]" value="fries">

JS

function togglePackage(isChecked,packageName) {
  //Choose one of the two below to use

  //Below selects the inputs by the class name
  var cbs = document.querySelectorAll("input."+packageName);
  //Or Below selects the inputs by the input name
  var cbs = document.querySelectorAll("input[name^="+packageName+"]");

  for(var i=0; i<cbs.length; i++) {
        //Since they are either checked and disabled (both true)
        //or unchecked and enabled (both false) we can just use
        //isChecked to set both at once.
        cbs.checked = isChecked;
        cbs.disabled = isChecked;
  }
}

//Then somewhere call the togglePackage function
//bx here would be the main checkbox that you want to 
//have toggling the other boxes, and "package1" is obviously
//the name or the class you gave the checkboxes.
togglePackage(bx.checked,"package1");