0

I created a php/javaScript automatisation of our form creation. Thus, when a dialog is created the button are added dynamicly and correctly, but I cannot access the JSON object in the function trigged on the click of the button.

Here is a exemple (The alert does not work, is not display):

aButtons[oGeneratedFormButtons[x].label] = function(){ alert(oGeneratedFormButtons[i].label); });

Can I pass data to the function or is there a way to know which button has been clicked.

Here is a simple sample : http://jsfiddle.net/DavidLaberge/h4Cgp/13/

David Laberge
  • 15,435
  • 14
  • 53
  • 83

2 Answers2

1

try using closure like this:

for (var x = 0; x < JSON.length; x++) {
    aButtons[JSON[x].label] = (function() {
        var i = x;
        return function() {
            alert(i);
            alert(JSON[i].label);
        }
    })();
}

Here is fiddle.

Molecular Man
  • 22,277
  • 3
  • 72
  • 89
0

Are you sure that the problem is not that you are using a different variable (i instead of x) inside the function? Because oGeneratedFormButtons[x].label should be accessible inside the function if it's accessible outside it.

aButtons[oGeneratedFormButtons[x].label] = function(){ alert(oGeneratedFormButtons[x].label); });
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192