Jeffrey Phung Jeffrey Phung - 14 days ago 5
Javascript Question

li input checkbox: how to get checked state javascript

I have access to each of the li[i] that returns what you see in the picture. An example would be

li[i].innerText
returns
business
. How can I get the
checked
state of each element?

element iteration


//loop through li elements in categories to add listeners
for(var i = 0 ; i < li.length; i++){
(function(i){
li[i].addEventListener('click', function(event) {
event.preventDefault();

//disallow repeats
if(checkedItems.indexOf(li[i].innerText) == -1){
checkedItems[counter] = li[i].innerText;
counter++;
console.log("added");
}

console.log(li[i].checked); //undefined
//remove element if unchecked from array
if(li[i].checked){
var index = checkedItems.indexOf(li[i].innerText);
console.log(li[i].innerText +": " + index);
checkedItems.splice(index, 1);
console.log("disabled");
counter--;
}
console.log(checkedItems);
});
}(i));

}




Answer

You need to get a reference to the input element, which you can do as follows:

var input = this.querySelector('input[type=checkbox]');

... and then you can use input.checked:

var li = document.querySelectorAll('li');

for(var i = 0 ; i < li.length; i++){
    li[i].addEventListener('click', function(event) {
      //event.preventDefault();
      var input = this.querySelector('input[type=checkbox]');
      console.log(this.textContent.trim(), input.checked);
    });
}
<ul>
<li>
    <span>test</span>
    <input type="checkbox">
</li>
</ul>