Search code examples
jqueryjquery-1.3

parse variable as JSON w/ jQuery


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.


Solution

  • 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.