0

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));

  }
LeggoMaEggo
  • 512
  • 1
  • 9
  • 24
  • Use `this` instead of `li[i]` within the event handler function and remove your closure. You can then get the state with the `checked` property – Rory McCrossan Nov 23 '16 at 22:47
  • I'm seeing a function in a for loop, is that a good idea? o_O – odedta Nov 23 '16 at 22:48
  • @odedta it's a closure - required in this case. – Rory McCrossan Nov 23 '16 at 22:49
  • @RoryMcCrossan Could you refer me to a place to learn more about this please? – odedta Nov 23 '16 at 22:49
  • 1
    See [this](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work), [this](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) and [this](http://stackoverflow.com/questions/2728278/what-is-a-practical-use-for-a-closure-in-javascript) – Rory McCrossan Nov 23 '16 at 22:50
  • Perfect, thank you very much :) – odedta Nov 23 '16 at 22:51
  • 3
    No problem. Just also note that while they aren't technically bad practice, they should be avoided unless absolutely necessary. – Rory McCrossan Nov 23 '16 at 22:52
  • Oh thanks for the info about closure's Rory! So what I did was I removed the closure and replaced all `li[i]`s with `this` inside the for loop. However everything returns as `undefined`. – LeggoMaEggo Nov 23 '16 at 23:01

1 Answers1

1

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>
trincot
  • 317,000
  • 35
  • 244
  • 286