0

Super sleepy and coding, not a good combination, if I was a surgeon, my patient would have passed away long time ago! So here goes my 1st question on this site:

My code:

function cAction(manipulatedElement) {
    console.log(manipulatedElement); //test parameter
    // some manipulation code...
}

var cboxes = document.getElementsByClassName('checkbox-toppings');

l = cboxes.length;
for(i = 0; i < l; i++) {
    cboxes[i].addEventListener('change',
        function() { cAction(i); },
        false
    );
}

When I check/uncheck a checkbox I only get "34" (the last checkbox) written to the console no matter which one is checked what gives? Shouldn't each event listener's callback remember the index number "i"?

Hope someone can help me with this.

Some HTML pasted from project:

<div class="toppings col-xs-6 col-sm-4 col-md-3">
    <div class="checkbox"><label>
        <input 
            type="checkbox" 
            class="checkbox-toppings" 
            id="topp1010" 
            value=""
            data-price="300"
        >
        <span class="toppings-text">pepperoni</span>
    </label></div>
</div>

<div class="toppings col-xs-6 col-sm-4 col-md-3">
    <div class="checkbox"><label>
        <input 
            type="checkbox" 
            class="checkbox-toppings" 
            id="topp1020" 
            value=""
            data-price="300"
        >
        <span class="toppings-text">ham</span>
    </label></div>
</div> 

<!-- and 32 more items like this -->

2 Answers2

0

Welcome to the concept of Closures.

the value of i is being captured or closed over by your handler ,so only the last value of i will get assigned.

change

 function(){cAction(i);}

to

(function(temp){return function(){
  cAction(temp);
}}(i))
Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
0

Use .bind to create a different function for each callback.

function cAction(manipulatedElement) {
    console.log(manipulatedElement); //test parameter
    // some manipulation code...
}

var cboxes = document.getElementsByClassName('checkbox-toppings');
l = cboxes.length;
for(i=0; i<l; i++) {
    cboxes[i].addEventListener('change', cAction.bind(cboxes[i], i), false);
}
bevacqua
  • 47,502
  • 56
  • 171
  • 285