JS - display elements on the screen from an object

Asked

Viewed 793 times

0

I need to assemble 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 the html, but using JavaScript?

I receive the object this way:

inserir a descrição da imagem aqui

1 answer

1


Assuming your object has this structure, you can assemble 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>

  • 1

    Thank you @Lucas, that’s exactly what I wanted to do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.