Danny Danny - 2 months ago 8
JSON Question

Javascript put JSON object values as text for radio buttons or list

So I'm new to web programming and know basically nothing. So if my practices are bad, I'm sorry.

I want to create a simple app that takes JSON objects and retrieves data from them and alters the HTML. What I exactly want to do is:

Get data from a JSON object like this one;
I only want to use vanilla javascript with no external libraries (so I learn) so jQuery for example is out of the question.

{
"id" : 21,
"question": "What is 2 + 8?",
"alternatives": {
"alt1": 2,
"alt2": 8,
"alt3": 10,
"alt4": 28
},
"answer" : "alt3"
}


I can get by key for example

var id = jSONobj.id


But how can I iterate over the alts in "alternatives" and set the values to my radio buttons:

<form action="" id="input4radio">
<input type="radio" name="ans"><br>
<input type="radio" name="ans"><br>
<input type="radio" name="ans"><br>
<input type="radio" name="ans"><br>
</form>


I assume that I use a for-loop but javascript is in my opinion very chaotic compared to java which is what I'm used to. So I don't know how to do such a function. Most answers I've seen either use jQuery or just get the values from the alt-list. They don't put the values anywhere.

Please help!

Answer

So the steps could be:

  • On the window onload event call a JS function
  • Get the form in DOM by it's ID
  • Loop through the 'alternatives' object inside your data
  • Create an input node on each iteration
  • Set the value of this node to the value of the key
  • Then append the new node to the form

    var data = {
        "id" : 21,
        "question": "What is 2 + 8?",
        "alternatives": {
            "alt1": 2,
            "alt2": 8,
            "alt3": 10,
            "alt4": 28
        },
        "answer" : "alt3"
    }
    
    function onLoad() {
        var form = document.getElementById('input4radio');
        for (alt in data.alternatives) {
            var newRadio = document.createElement('input'); 
            newRadio.type = 'radio';
            newRadio.value = data.alternatives[alt];
            form.appendChild(newRadio); 
            form.appendChild(document.createElement('br'));
        }
    
    }
    
    window.onload = onLoad;
    

And then have an empty form in HTML:

    <form action="" id="input4radio">

I came from a Java background too - in time I think you'll come to see the chaos as flexibility :)