0

I have a bunch of divs that when they are clicked I want to update some data that is associated with it. I have a click event registered with the div but I can't figure out how to pass the data into the click event handler along with it. I've looked at quite a few other similar SO questions but haven't found a working solution yet.

I want to basically be able to click a box and pass the number along with it:

var numbers = ['one', 'two', 'three', 'four'];
var container = document.getElementById('container');

for (var i = 0; i < numbers.length; i++){    
    var checkbox = document.createElement('div');
    checkbox.setAttribute('class','checkBtn');

    var save = function(){
        console.log(numbers[i]);
    }
    $(checkbox).click(function(){
        save();
    });
    container.appendChild(checkbox);
}

http://jsfiddle.net/1qrvxe1j/

Chase Roberts
  • 9,082
  • 13
  • 73
  • 131

2 Answers2

2

You could use JQuery .each to iterate through the array.

$.each(numbers, function(index, num) {
    var checkbox = document.createElement('div');
    checkbox.setAttribute('class','checkBtn');

    $(checkbox).click(function(){
        console.log(num);
    });
    container.appendChild(checkbox);
});
Stryner
  • 7,288
  • 3
  • 18
  • 18
1

You have to use closures... try his code.

var numbers = ['one', 'two', 'three', 'four'];
var container = document.getElementById('container');

var save = function (arg1) {
    console.log(arg1);
}

var clickEvent = function (i) {
    return function () {
        save(numbers[i]);
    };
}

for (var i = 0; i < numbers.length; i++){    
    var checkbox = document.createElement('div');
    checkbox.setAttribute('class','checkBtn');

    $(checkbox).click(clickEvent(i));

    container.appendChild(checkbox);
}
Callebe
  • 1,087
  • 7
  • 18
  • Ok, so this works. But I have a hard time following why I have to do it this way. – Chase Roberts Aug 21 '14 at 02:06
  • 1
    When you do a for loop and declare a function inside this for loop accessing the var i, all functions declared inside this for loop will access the last value of var i. When you use a closure defined in `clickEvent`, each function will receive a copy of the var i in the moment that clickEvent is called. If i wasn`t clear, please, follow this link https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Closures – Callebe Aug 21 '14 at 02:11
  • The @Ninsly code should work too. – Callebe Aug 21 '14 at 02:11
  • I read the duplicate answer explanations and I understand it now. – Chase Roberts Aug 21 '14 at 02:12