Reputation: 13
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);
Upvotes: 0
Views: 145
Reputation: 1459
There are still several attributes that cannot be applied by the way you are trying to. So, you will have to use the older .setAttribute
method. For example on your cb
object. Try instead of .onClick
, try this:
cb.setAttribute('onClick','function(){myFunction(i);}');
Hope this helps!
Upvotes: 0
Reputation: 6908
This is a pretty common scope problem people have. The issue is that the 'i' value at the time you create the function isn't the same 'i' value that's set when you call the function, so the 'i' every time it gets called will always be 3.
The simplest way around this is to simply grab the value from your 'this' for the element, e.g.:
cb.onclick = function(){myFunction(this.name);}
If you don't want it to be the string name, just set it earlier like so:
cb.counter = i;
cb.onclick = function(){myFunction(this.counter);}
Upvotes: 2