skip to Main Content

I have a json file that is created based on user input and the number of items in the json file can vary. I want to loop through all items in the json file in a Javascript function and display each item line by line in the HTML script.

The sample JSON file looks like this:

data={"What is your name": "Jason", 
       "What is your favorite color": "Blue",
        When is your birtyday?", "Jan 15"}

In the HTML file, once a certain button is clicked, each item in the json file should appear as a Question/Answer pair. For example, "What is your name: should appear in the first "question" input box, and "Jason" should appear in the first "answer" input box. For the exmple above, since there are three items, there should be 6 lines of input html tags, 3 of which for the questions and the other three for the answers. If the JSON file has, for example, 5 items, there should be 5 sets of question/answer inputs. Here’s my HTML code:

<input id="open-btn" class="right-button"></input>
<form class="form-container" action="mailto:?subject=Answers" method="post" enctype="text/plain" >

      <!-- Question & Answer Input Sets: I want to loop this --!>
      <div class="form-group">
           <label for="question1">Question </label>
           <input type="text" id="question1" class="form-input" name="Question1">
      </div>
      <div class="form-group">
           <label for="answer1">Answer </label>
           <input type="text" id="answer1" class="form-input" name="Answer1">
      </div>

      <button type="submit" class="btn btn-primary">Submit</button>
</form>

In Javascript, I read the json file and tried to loop through all keys(questions) and values (answers) and pass them to the question and answer inputs in the HTML. But I’m not sure how to introduce the loop in the html component. For now, I have only one input for questions (id = question1) and answers(id=answer1) in HTML and it just displays the first item in the json file.

const open = document.getElementById("open-btn");

open.addEventListener('click', () => {
    $.getJSON("../static/data.json", function(data) {
        $.each(data, function (key, value) {
            document.getElementById("question1").value = key
            document.getElementById("answer1").value = value     
        }
            
            )
        
        console.log("Log Data:",data)
    
    });

How can I loop through all items in the json file and display them in html line by line? For example, if there are three items in the json file like the example above, I want the 6 lines of inputs, 3 of which are for questions and the other 3 for answers. Since the length of the json file can vary, I can’t create the pre-determined number of input sets in my HTML file.

Or is it possible to read the json file, and store the dictionary as a variable in the Javascript function and use that variable in a for loop in html?

2

Answers


  1. You can create a function to add an element to HTML such as

    function addPair(parent,type,text,pairId){
    
        var formGroup = document.createElement("div");
        formGroup.className = "form-group";
    
        var typeLabel = document.createElement("label");
        typeLabel.htmlFor = type+pairId;
        typeLabel.innerText = text;
    
        var inputText = document.createElement("input");
        inputText.type = "text";
        inputText.id = type+pairId;
        inputText.className = "form-input";
        inputText.name = type+pairId;
        inputText.value = text;
    
        formGroup.appendChild(typeLabel);
        formGroup.appendChild(inputText);
    
        parent.appendChild(formGroup);
    }
    

    and then use it like this

    const open = document.getElementById("open-btn");
    var pairs = 0;
    var formContainer = document.getElementById("form-container");
    
    open.addEventListener('click', () => {
        $.getJSON("../static/data.json", function(data) {
            $.each(data, function (key, value) {
                addPair(formContainer,"Question",key,pairs);
                addPair(formContainer,"Answer",value,pairs);
                pairs++;
            }
    
                )
    
            console.log("Log Data:",data)
        
        });
    

    you can see an example here

    Hope this helps!

    Login or Signup to reply.
  2. You need to create new elements within the each method.

    Since you appear to be using Jquery, we can insert new elements into our HTML using Jquery’s appendTo method. To avoid duplicate IDs in our HTML and to bind each <label> to each corresponding <input>, we use a simple counter defined as i.

    data = {
      "What is your name": "Jason",
      "What is your favorite color": "Blue",
      "When is your birtyday?": "Jan 15"
    };
    
    const open = document.getElementById("open-btn");
    
    var i = 1;
    
    open.addEventListener('click', () => {
          $("#open-btn").prop('disabled', true);   // to avoid spamming.
          
       // $.getJSON("../static/data.json", function(data) {      
          $.each(data, function(key, value) { 
             $("<div />", { "class":"form-group" })
               .append($("<label />", { for:"question" +i, text:"Question " +i}))
               .append($("<input />", { type: "text", id:"question"+i, value: key }))
               .appendTo(".example-output");
             $("<div />", { "class":"form-group" })
               .append($("<label />", { for:"answer" +i, text:"Answer " +i}))
               .append($("<input />", { type: "text", id:"answer"+i, value: value }))
               .appendTo(".example-output");
            i++;
          })   
       // });
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="" id="open-btn">open btn</button>
    <form class="form-container" action="mailto:?subject=Answers" method="post" enctype="text/plain">
          <div class="example-output"></div>
          <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search