0

I have a json file:

{
  "questions": [
    {
      "title": "01. q1",
      "type": "dropdown",
      "options": [
        {
          "1",
          "2",
          "3"
        }
      ]
    },
    {
      "title": "q2",
      "type": "multiple_choice",
      "options": [
        "1",
        "2",
        "3",
        "4",
        "5"
      ]
    },

And I'm trying to write a for loop in a js file in order to go through the data, and if the question type is "dropdown", display an html dropdown selectors, "multiple choice" would get buttons, etc:

console.log = function(message) {
    document.getElementById('q_1').innerHTML = message;
};

console.log2 = function(message) {
    document.getElementById('q_2').innerHTML = message;
};

$.getJSON("generated.json", function(json)) {
  for (var i = 0; i<json.questions.length; i++) {
    if(json.questions[i].type=="drop_down") {

    }
  }
}

I'm really confused as to how to do this dynamically and not hard code most of the code. Is there a way for this to be written concisely without having to write out every option/question in an html file and just read and generate questions from the json file?

3
  • 1
    function(json)) <-- remove the 2nd ) and put it after the final }. Other than that it looks fine. Incidentally, did you really want to override the console log method?? Commented Feb 4, 2018 at 17:44
  • Also try not to mix DOM JS and jQuery. It makes it even more confusing Commented Feb 4, 2018 at 17:45
  • Maybe document.createElement can help you Commented Feb 4, 2018 at 17:49

1 Answer 1

0

this is the way you can use it :

var data = [
    {
      "title": "01. q1",
      "type": "dropdown",
      "options": ["1","2","3"]
    },
    {
      "title": "q2",
      "type": "multiple_choice",
      "options": ["1","2","3","4","5"]
    }
];
 $(document).ready(function(){
    $(".hello").append("<p>hello</p>")
    var s ="" ; 
    for(var i=0;i<data.length ; i++){
      if(data[i].type == "dropdown"){
        s += "<p>dropdown</p>";
        
      }
      else if(data[i].type == "multiple_choice"){
        s += "<p>multiple_choice</p>"
      }
    }
    
    $(".hello").append(s);
    
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hello">

</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.