0

I have this script in my html that dynamically adds an event handler to checkboxes but the problem is when the checkbox is clicked it doesnt return the value that was used in the called function but rather returns the total amount of items in the array of checkboxes.

<script>


 var channelV = document.querySelectorAll('input');

function loadstart(){


for(var i = 0; i < 4; i++) {
  channelV[i].addEventListener('change', function(){
    SwitchChannel(i);

  });
alert(i);
  }
}
</script>

Not all my scripts are included.

  • `function() { SwitchChannel(i); }` can just be `() => SwitchChannel(i)` – Gage Hendy Ya Boy Dec 22 '17 at 17:42
  • There is not much to work with here, you should post the `SwitchChannel` definition at least. – Gage Hendy Ya Boy Dec 22 '17 at 17:42
  • https://stackoverflow.com/questions/2236747/use-of-the-javascript-bind-method#10115970 You could also use bind to create the callback for the event listener, providing it the i as an argument. `channelV[i].addEventListener('change', SwitchChannel.bind(channelV[i], i));` – Taplar Dec 22 '17 at 17:44

0 Answers0