Use html attribute as javascript variable

1

I'm developing a PHP system that uses an extension for dynamic forms, where I can click a button to add fields (EX: A request can have multiple items, where items are fields added dynamically).

The extension I use (I do not think it is necessary to mention, since the problem is not with it) has in its configuration a parameter where I can specify the limit of fields that can be added dynamically, being infinite or not.

When the extension is rendered, it generates a code snippet in javascript, where in this snippet is a variable that contains a JSON with the previously set parameters, among them the "limit" parameter, which is the parameter I I want to change at runtime.

So far so good ... The problem is that such a variable that contains JSON has a random suffix in the name, such as dynamicform_5ed2807a or dynamicform_7fg2802c .

The name of this variable I can find because there is a div with the dynamicform-wrapper fixed class that contains the data-dynamicform attribute, and the value of this attribute is exactly the name of the variable.

Given this, I tried to do this, without success:

var x = $(this).attr('data-dynamicform');
console.log(x.limit); // Note que limit é o nome da 'key' que eu quero pegar o valor

In the example above, it returns undefined , and should return an integer, which is the field limit.

EDIT
Follow JSFiddle link: link

How can I solve this problem? Many thanks!

    
asked by anonymous 13.09.2016 / 19:46

1 answer

1

If this variable that is generated by PHP is in the global scope you can access it via window object with brackets.

You can then access it like this:

var chave = $(this).attr('data-dynamicform');
var x = window[chave];
console.log(x.limit);

jsFiddle: link

    
13.09.2016 / 20:05