0

Script:

for (var i = 0; i < products.length; i++) {
    for (var j = 0; j < products.length; j++) {
        $(document).on('change', $(products[i][j].checkbox) , function () {
            products[i][j].checked ? products[i][j].checked = false : products[i][j].checked = true;
        };
    }
}

How I cant get products[i][j] in my event function?

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44
AlexAstanin
  • 343
  • 1
  • 4
  • 14
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake – Arun P Johny Sep 16 '14 at 05:41
  • Looks like an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. What are you really trying to do? – Evan Davis Sep 16 '14 at 05:42
  • There is a better solution in this case than the one provided by the duplicate question: Make use of the `data` parameter of the event handler: https://api.jquery.com/on/#passing-data. Also, `$(products[i][j].checkbox)` seems wrong. The argument must be a selector, not a jQuery object. I recommend to read the documentation: https://api.jquery.com/on/, https://learn.jquery.com/events/event-delegation/. However since you are not really explaining what the problem is, we can't really help. – Felix Kling Sep 16 '14 at 05:42

1 Answers1

0

Use an anonymous function that's invoked immediately to create a new scope.

This way the anonymous function of the change event becomes a closure.

for (var i = 0; i < products.length; i++) {
    for (var j = 0; j < products.length; j++) {
        //anonymous function (outer function)
        (function() {
            var product = products[i][j];
            //now the anonymous function of the change event will be called
            //within this new scope, with each unique product in it
            $(document).on('change', function () {
                //this is function is now a closure with scope of the outer function
                product.checked ? product.checked = false : product.checked = true;
            };
        })();
    }
}

The scope of the product variable will fall inside the anonymous function closure and each change event will have a unique product value associated.

Fiddle: http://jsfiddle.net/mattdlockyer/t2h50aun/1/

Closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

Immediately Invoked Functions: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression

There seems to be another issue with your code, why are you checking document for change?

mattdlockyer
  • 6,984
  • 4
  • 40
  • 44