Using only JavaScript, and regarding my code, how can i check and uncheck with a checkbox as trigger the whole checkbox array?

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

2
MauriceNino On Best Solutions

You can't give multiple elements the same ID. Give all elements the same Class and select them with getElementsByClassName like shown in my snippet.

<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
zer00ne On
  • All ids must be unique: MyId change to classes or unique ids
  • Wrapped a <form> tag around everything which allows us to use HTMLFormElement and HTMLFormControlsCollection API to easily access <form> tags and all form controls (ie <input>, <textarea>, etc).

  • Details commented in demo.

// 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;
}
<form id='main'>

  <input type="checkbox" name="trigger" id='trigger' checked>

  <input type="checkbox" name="idArray[]" id="id1" value="1" checked>
  <input type="checkbox" name="idArray[]" id="id2" value="2" checked>
  <input type="checkbox" name="idArray[]" id="id3" value="3" checked>

</form>