JS - display elements on the screen from an object

0

I need to mount a questionnaire on the screen with questions and alternatives brought from a database, it is possible to mount the screen with label and radiobuttons without putting a foreach in html , but using JavaScript ?

I get the object this way:

  

    
asked by anonymous 01.12.2016 / 15:11

1 answer

1

Assuming your object has this structure, you can mount the components and include them in a div using innerHTML :

var obj = {
  "perguntas": [{
    "campanhaId": 1,
    "id": 1,
    "nome": "pergunta 1",
    "respostas": [
      "alternativa A",
      "alternativa B",
      "alternativa C"
    ]
  }, {
    "campanhaId": 2,
    "id": 1,
    "nome": "pergunta 2",
    "respostas": [
      "alternativa A",
      "alternativa B",
      "alternativa C"
    ]
  }]
};
var div = document.getElementById("perguntas")
  , texto = '';
obj.perguntas.forEach(function(item){
  texto += "<label>" + item.nome + "</label><br/>";
  item.respostas.forEach(function(res){
    texto += "<input type='radio' name='" +item.campanhaId+ "'>" + res + "</input><br/>";
  });
});

div.innerHTML = texto;
<div id="perguntas"></div>
    
01.12.2016 / 15:36