V
V
Victor L2017-02-28 01:15:50
JavaScript
Victor L, 2017-02-28 01:15:50

How to create a form from json (object)?

Given such a design, does it need to be converted into a form?
q0 respectively 1 question, he has three answers, a1 is the correct one

const data = {
  "q0":{
    "question":"1+1=?",
    "answer":{
      "a0":"1",
      "a1":"2",
      "a2":"0"
    },
    "right":["a1"]
  },
  "q1":{
    "question":"2*2=?",
    "answer":{
      "a0":"1",
      "a1":"4",
      "a2":"5"
    },
      "right":["a1"]
  }
};

I immediately made such a sheet, but I lost the answers and the most interesting thing is that there should be a checkbox installed against the correct answer?
$.each(data, key=>{
   $('table.table-test > tbody').append('<tr class="q-template"><td class="width-40">'+key+'</td><td style="vertical-align:top;"><textarea rows="4" name="'+key+'[question]" class="form-control">'+data[key].question+'</textarea></td><td><table class="table table-bordered table-answer"><tr class="a-template"><td><input class="form-control" type="text" placeholder="Ответ" name="'+key+'[answer][a1]"></td><td class="width-80"><div class="checkbox"><label>  <input type="checkbox" name="'+key+'[right][]" value="a1"> true</label></div></td><td class="width-80"><button class="delete-answer fa fa-trash btn btn-danger" type="button"></button></td></tr><tfoot><tr><td colspan="3"><button class="add-answer">Добавить ответ</button></td></tr></tfoot></table></td><td><button class="delete-question fa fa-trash btn btn-danger"></button></td></tr>');
});

Sandbox
What is the best way to parse all this and put down a checkbox? I'm more interested in the solution itself.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2017-02-28
@Fzero0

See if there are several answers, if yes, then do it with radio buttons. If the answer is one, then it makes an input. Make each into each.
It is better, of course, to write a class in which there will be methods renderRadio, renderCheckbox, RenderInput, RenderForm. We pass json into it and parse it, incrementing one $html variable, for example. and at the end passes the $html content to the desired div, table or whatever you have

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question