views:

301

answers:

3

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.

+4  A: 

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.

Chacha102
GAH - thanks now I just need to know how to get the values from the underlying answer objects, I am looping through them like this: for(var i =0; i < json.answers.length; i++) { var item = json.answers[i]; }how do I get the values out of this?
Slee
json.answers[i].84 would get the first value.
Chacha102
yeah the numbers are always changing - I will never know them ahead of time
Slee
so you need to change the format of the array then.
Chacha102
A: 

Normally you would just use a each statement like below:

 jQuery.each(json.answers, function(i, val) {
   $("#" + i).val() = val;
 });
Nick Clarke
A: 

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.

Slee