【发布时间】:2014-10-30 12:18:13
【问题描述】:
我期望表单中的 json 数据格式如下 -
{
courseId: 4,
lectureId: 5010,
popupTime: 3,
questions: [
{
title: "Which is the Capital of India 2",
_id: "5450dff18f7cde8b4ed4ae3d",
answers: [
{
answer: "Delhi",
correct: true,
},
{
answer: "Bangalore",
correct: false,
},
{
answer: "Mumbai",
correct: false,
},
{
answer: "Chennai",
correct: false,
}
]
},
{
// second object in questions array.
}
]
}
如何在前端设计表单,让用户可以输入一个问题(可以是多个)然后可以
输入与该问题相关的答案。我什至想在 answers 对象中存储一点,表明它是否是
答案是否正确。(通常来自checkbox 或radio button)。
到目前为止我已经尝试过 -
<form id="aj">
<input type="text" name="questions[][title]" value="" placeholder="Question Title">
<input type="text" name="answers[]" value="" placeholder="Answer 1">
<input type="text" name="answers[]" value="" placeholder="Answer 2">
<input type="text" name="answers[]" value="" placeholder="Answer 3">
<input type="text" name="answers[]" value="" placeholder="Answer 4">
<button>Send</button>
</form>
$( "#aj" ).submit(function( event ) {
event.preventDefault();
var o = {};
var a = $( "#aj" ).serialize();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
console.log(o);
});
所以在序列化之后我得到了 -
{
questions: [ { title: 'Question 1' } ],
answers: [ 'answer 1', 'answer 2', 'answer 3', 'answer 4' ]
}
但我需要问题是array of object 问题。每个问题对象都有一系列答案。
关于如何实现这一点的任何指示?
【问题讨论】:
-
您遇到了什么具体问题?
-
我已经用我正在尝试的内容更新了这个问题。我做错了什么?
标签: javascript html json forms