PRVS PRVS - 6 months ago 23
jQuery Question

Verify checked checkbox javascript

I'm trying to update in "real time" if I check and uncheck in a list of checkboxs.

With this code:

window.onload = function () {
var input = document.getElementById('listTaxi');

function check() {
var a = input.checked ? "checked" : "not checked";
console.log(a);
}
input.onchange = check;
check();
}


I can do this for one checkbox, but how can I make for multiple checkboxs? A list(div) of checkboxs?

Thanks!!

Answer

Assign a class on all checkboxes you want to check if checked or not.

Checkboxes

<input type="checkbox" class="checkboxes" id="checkbox1"/>
<input type="checkbox" class="checkboxes" id="checkbox2"/>
<input type="checkbox" class="checkboxes" id="checkbox3"/>
<input type="checkbox" class="checkboxes" id="checkbox4"/>

Pure Javascript

// getting all checkboxes
var checkboxes = document.getElementsByClassName('checkboxes');

// go through all checkboxes
for(var i = 0; i <= checkboxes.length - 1; i++){
  checkboxes[i].onchange = function(e){
    alert('Element with id ' + e.target.getAttribute('id') + ' is checked ' +e.target.checked);
  }
}

Codepen http://codepen.io/todorutandrei/pen/rLBQOX

Or you can use JQUERY - is it more simple

$('.checkboxes').change(function(){
  var item = $(this);
  alert('Element with id ' + item.attr('id') + ' is ' + item.is(':checked'));
})

Codepen http://codepen.io/todorutandrei/pen/MegzwR