Reputation: 28248
I am trying to populate a form with a list of questions and radio buttons. When the page is loaded I have a variable that contains the answers they have so far as a string in JSON format:
var json = '{ "answers" : [{"84" : "Y" },{"85" : "Y" },{"86" : "Y" },{"87" : "Y" },{"88" : "Y" },{"89" : "N" },{"90" : "N" },{"91" : "N" },{"92" : "Y" },{"93" : "N" },{"94" : "Y" },{"95" : "N" },{"96" : "N" },{"97" : "Y" }]}';
I need to loop through the answers and find the radio button with the ID matching the number IE id="84" and set it's value based on the corresponding value (Y).
seems like getJSON is what I should be looking at but I do not need to make the call to get the data since I already have it.
Upvotes: 2
Views: 2319
Reputation: 28248
Got it, removed the quotes as mentioned above added a class that matched the ID so I could select all elements for a given ID:
for(var i =0; i < json.answers.length; i++) {
var item = json.answers[i];
for (var j in item) {
$('.' + j).each(function(){
if ($(this).attr("value") == item[j]) $(this).attr("checked", true);
});
}
}
I am sure there is probably a more elegant solution but this is working very well so far.
Upvotes: 0
Reputation: 1282
Normally you would just use a each statement like below:
jQuery.each(json.answers, function(i, val) {
$("#" + i).val() = val;
});
Upvotes: 0
Reputation: 61557
You could just remove the quotes on the outside and it would already be in the right format.
var json = {
"answers" : [{"84" : "Y" },
{"85" : "Y" },
{"86" : "Y" },
{"87" : "Y" },
{"88" : "Y" },
{"89" : "N" },
{"90" : "N" },
{"91" : "N" },
{"92" : "Y" },
{"93" : "N" },
{"94" : "Y" },
{"95" : "N" },
{"96" : "N" },
{"97" : "Y" }
]
};
Unlike some other formats, JSON is based on the actual language, which means that you can use the JSON format in regular coding. It is fairly easy to write JSON.
Upvotes: 4