Reputation: 541
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?
//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));
}
Upvotes: 0
Views: 2048
Reputation: 350841
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>
Upvotes: 1