1

I am using an event listener on a checkbox and I need to be able to pass in an index. Currently it is always saving the index as 2. The length of the groups array is 2.

for(var i = 0; i < groups.length; i++) {
    var input1 = document.createElement('input');
    input1.type = "checkbox";
    input1.addEventListener('click', function () {
        console.log(i);
    }, false);
}
Mardymar
  • 419
  • 3
  • 14
  • Do you want to count the occurrence of a click? In a properly formed `for` loop, that's as far as you'll get is 2 if that's the total of `groups.length`. What is the problem? Btw, please provide the HTML as well, or how else would we know what to expect? – zer00ne Mar 09 '16 at 02:42
  • I want to be able to pass the current index of the groups array into another function. This code should create a 'checkbox' for each item in group that contains a reference to the specific group. – Mardymar Mar 09 '16 at 02:48

1 Answers1

1
for(var i = 0; i < groups.length; i++) {
    (function(){
    var parent = document.getElementById("sidebar-wrapper");
    var input1 = document.createElement('input');
    input1.type = "checkbox";
    input1.addEventListener('click', function () {
        var j = i;
        var iMinus1 = j-1;
        console.log(j);
        setSelectedGroups(this, groups[iMinus1]);
    }, false);
    })()
}

Your index is always being saved as two because the function is being called asynchronously. It's checking the index not at the time you DEFINE the event listener, but at the time it's being CALLED. This means that the loop has probably already been terminated by the time you call the function, so it sees the index at it's ultimate value of 2. What this code does is execute an immediately invoked function so that the index, at the time you define the event listener, is saved in a closure, and it refers back to that closure.

whatoncewaslost
  • 2,216
  • 2
  • 17
  • 25
  • I created a jsFiddle to test this, but the console is not logging anything. https://jsfiddle.net/Mardymar/ynjebk28/ – Mardymar Mar 09 '16 at 02:30
  • In that JS Fiddle, I don't see an element to click, a checkbox, at all. Is that what you're seeing? – whatoncewaslost Mar 09 '16 at 02:39
  • It's easier to use `let`. –  Mar 09 '16 at 02:39
  • You were right Oceans. I needed to call the checkbox in order for it to log anything. I guess that's what I get for brevity. Adding var j = i made my code work as expected. – Mardymar Mar 09 '16 at 02:52