2014-12-02 21 views
-1

我有一個表單,我希望能夠編輯/更改數據。數據來自一個JSON文件,看起來像這樣:如何從json生成html表單輸入?

data:{ 
    "contest_id": 26, 
    "question": { 
     "title": "what is the capital of germany?", 
     "question_id": 27, 
     "answers": [ 
      { 
      "answer_id": 76, 
      "answer": "Hamburg", 
      "correct" : "false"    
      }, 
      { 
      "answer_id": 77, 
      "answer": "Munich", 
      "correct" : "false" 
      }, 
      { 
      "answer_id": 78, 
      "answer": "Berlin", 
      "correct" : "true" 
      } 
     ] 
    } 
} 

我基本的HTML(從編輯彈出)看起來是這樣的:

// this is just a snippet of the entire form 

<input type="radio" id="answerChk_" name="correct"> 
<input type="text" required></input> 
<input type="hidden" id="answer_" value=""></input> 

所以,我想實現的是獲取和注入answer + answer_id的答案,如果答案是正確的 - >以便我可以發佈和更新數據庫。

這怎麼可能?我不想使用任何插件...

我感謝任何幫助!

+0

您使用了哪些搜索詞? – Jonast92 2014-12-02 14:46:23

+0

@vch你是絕對正確的,我的錯誤...不應該在那裏... – Steve 2014-12-02 14:52:22

+0

'''s是自動關閉... – War10ck 2014-12-02 14:55:29

回答

1

您可以循環trought數組,並追加像這樣的html:

$.each(data.question.answers, function() { 
    $("YourForm").append('<input type="radio" id="answerChk_'+ this.answer_id +'" name="correct" selected="'+this.correct +'">'); 
    $("YourForm").append('<input type="text" required>'+ this.answer+'</input>'); 
    $("YourForm").append('<input type="hidden" id="answer_'+ this.answer_id +'" value="'+ this.answer+'"></input>'); 
}); 

我希望你的想法。

+0

非常感謝!這適用於我:-) – Steve 2014-12-02 15:19:01