Skip to content
Advertisement

Check | Uncheck – Checkbox Array By Id

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

Advertisement

Answer

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 />
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement