I have the following JSON Object:
{
"a1_1_on" : "on",
"a1_1_thr" : "",
"a1_2_on" : "on",
"a1_2_thr" : "",
}
and I want using a for loop to check the fields for example:
for (var i=1; i<2; i++) {
//alarm
var al = 'ai_' + i + '_on';
//alarm threshold
var althr = 'ai_' + i + '_thr'
//console.log(form_infos.al);
if(form_infos.al == "on" && form_infos.althr == "") {
alert("Alarm for Analog " + i + "is on and you did not specified a threshold. Please specify a threshold before submittiing");
return false;
}
}
But it shows undefined if I do console.log(form_infos.al). Any suggestions?
There are several errors in your code.
First of all, In JSON ‘:’ is used between key and value, so it has to be
by the way this is not JSON, but a simple Javascript Object. JSON would be the String representation of that Object.
Second, your string to index the elements has a typo, you have
in your Object but you use
in your code (i instead of 1)
Third, al is not an subobject of form_infos, but a variable containing a string. To access a subobject with a string index use
instead of
That’s it