How to get the value of checked checkbox in vanilla JavaScript?

Tags:



I am working on this snippet. Why am I not able to get the value of any checked checkbox with class .shapes?

document.getElementsByName('shapes').onclick = function() {
  var checkboxes = document.getElementsByName('shapes')[0].value;
  console.log(checkbox.value);
}
<div class="js-shapes">
  <span class="ib">
          <input type="checkbox" name="shapes" class="shapes" value="circle" id="cb-circle"> <label for="cb-circle">Circle</label>
        </span>
  <span class="ib">
          <input type="checkbox" name="shapes" class="shapes" value="diamond" id="cb-diamond"> <label for="cb-diamond">Diamond</label>
        </span>
  <span class="ib">
          <input type="checkbox" name="shapes" class="shapes" value="square" id="cb-square"> <label for="cb-square">Square</label>
        </span>
  <span class="ib">
          <input type="checkbox" name="shapes" class="shapes" value="triangle" id="cb-triangle"> <label for="cb-triangle">Triangle</label>
        </span>
  <span class="ib">
          <input type="checkbox" name="shapes" class="shapes" value="all" id="cb-all" checked> <label for="cb-all">all Shapes</label>
        </span>

</div>

Answer

You can simply use querySelectorAll method and use forEach method to check which checkbox was clicked using addEventListener with change function in it.

Edit: If you want to get the value of checkbox when checked you can checked property and then display its value.

Live Demo

let allCheckBox = document.querySelectorAll('.shapes')

  allCheckBox.forEach((checkbox) => { 
  checkbox.addEventListener('change', (event) => {
    if (event.target.checked) {
      console.log(event.target.value)
    }
  })
})
<div class="js-shapes">
  <span class="ib">
    <input type="checkbox" name="shapes" class="shapes" value="circle" id="cb-circle"> <label for="cb-circle">Circle</label>
  </span>
  <span class="ib">
    <input type="checkbox" name="shapes" class="shapes" value="diamond" id="cb-diamond"> <label for="cb-diamond">Diamond</label>
  </span>
  <span class="ib">
    <input type="checkbox" name="shapes" class="shapes" value="square" id="cb-square"> <label for="cb-square">Square</label>
  </span>
  <span class="ib">
    <input type="checkbox" name="shapes" class="shapes" value="triangle" id="cb-triangle"> <label for="cb-triangle">Triangle</label>
  </span>
  <span class="ib">
    <input type="checkbox" name="shapes" class="shapes" value="all" id="cb-all" checked> <label for="cb-all">all Shapes</label>
  </span>

</div>


Source: stackoverflow