检查取消选中-按ID的复选框数组

时间:2019-04-11 10:49:32

标签: javascript

仅使用JavaScript,并针对我的代码,如何通过复选框选中和取消选中复选框来触发整个复选框数组?

<script language="JavaScript">

 var aux=true;

 function ToggleAllCheck(id) {

  var VarInput = document.getElementById(id);

  for(var i = 0; i < VarInput.length; i++){

   VarInput[i].checked = (aux == true) ? false : true;

  }

  aux = (aux == true) ? false : true;

 }

</script>

<input type="checkbox" name="Trigger" onclick="ToggleAllCheck('MyId')" checked /> <!-- Trigger Checkbox -->

<input type="checkbox" name="MyIdArray[]" id="MyId" value="1" checked />
<input type="checkbox" name="MyIdArray[]" id="MyId" value="2" checked />
<input type="checkbox" name="MyIdArray[]" id="MyId" value="3" checked />

2 个答案:

答案 0 :(得分:2)

您不能为多个元素赋予相同的ID。将所有元素都设置为同一类,并使用getElementsByClassName进行选择,如我的代码片段所示。

<script language="JavaScript">

 var aux=true;

 function ToggleAllCheck(className) {

  var varInput = document.getElementsByClassName(className);

  for(var i = 0; i < varInput.length; i++){

   varInput[i].checked = (aux == true) ? false : true;

  }

  aux = (aux == true) ? false : true;

 }

</script>

<input type="checkbox" name="Trigger" onclick="ToggleAllCheck('MyClass')" checked /> <!-- Trigger Checkbox -->

<input type="checkbox" name="MyCheckbox1" class="MyClass" value="1" checked />
<input type="checkbox" name="MyCheckbox2" class="MyClass" value="2" checked />
<input type="checkbox" name="MyCheckbox3" class="MyClass" value="3" checked />

答案 1 :(得分:1)

  • 所有ID必须唯一: MyId 更改为类或唯一ID
  • 在所有内容之间使用<form>标签,这使我们能够使用HTMLFormElement和HTMLFormControlsCollection API轻松访问<form>标签和所有表单控件(即<input>,{{1} }等)。

  • 详细信息在演示中进行了评论。

<textarea>
// Reference the <form>
var main = document.forms.main;

// Register <form> to the change event
main.onchange = allChx;

// When change event is triggered, allChx() is called
function allChx(event) {

  // Reference the changed form control (ie #trigger)
  var tgt = event.target;

  // Collect all form controls with the name of idArray[]
  var all = this.elements["idArray[]"];

  /*
  if event.target is #trigger...
  if #trigger checked then status is true otherwise false
  Loop through the all collection and check or uncheck all
  checkboxes with the name of idArray[]
  */
  if (tgt.matches("#trigger")) {
    let status = tgt.checked ? true : false;

    for (let a of all) {
      a.checked = status;
    }
  }
  return false;
}