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.