I have been trying add an onclick event for a set of checkboxes I create via JS but it isn't doing what I expect.
At the end of the script, after it builds the checkboxes within the "checkboxes" div, I expect each box to call the handler with a different argument i. It appears the handlers are all using the current value of i, actually incremented from where it was being used.
What am I missing here ???
function initialize() {
console.log("enter initialize");
console.log("create checkboxes");
for ( i=0; i<4; i++){
var span1 = document.createElement('span');
span1.innerHTML = i;
var cb = document.createElement('input');
cb.type = "checkbox";
cb.name = i.toString();
cb.onclick = function(){myFunction(i);}
console.log(i, cb.name, cb.onclick);
var checkboxes = document.getElementById("checkboxes");
checkboxes.appendChild(span1);
checkboxes.appendChild(cb);
console.log("cb="+cb.toString());
}
}
function myFunction(b){
alert(b);