0

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);
1
  • Can you make a fiddle? Commented May 12, 2014 at 0:12

2 Answers 2

2

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);}
Sign up to request clarification or add additional context in comments.

3 Comments

Got to it before I did. Here's a JSFIDDLE for your answer.
Josh, you hit the nail on the head. Thanks
Gary, thanks. I've not used JSFIDDLE but it looks like a great resource. Thanks.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.