我正在准备一个表单元素,如图像http://i.imgur.com/aJdS6nm.png?1中所示,添加更多按钮,可以添加更多此类textfields
对。
元素代码如下:
<td class="answer_choice_<?php echo $question_id ?>" >
<span style="float:left; font-size: 14px;">If This Happens...</span>
<textarea rows="2" cols="20" name="happens" style="float:left; <?php echo $text_style; ?>" class="answer_choice_<?php echo $question_id ?>" value=""
></textarea>
<span style="float:left; font-size: 14px;">I Should...</span>
<textarea rows="2" cols="20" name="should" style="float:left; <?php echo $text_style; ?>" class="answer_choice_<?php echo $question_id ?>" value=""></textarea></td>
将serializeArray()
应用于获取值:
yellow_flags_ser = $('.yellow_flag_clone_'+qa_id+' :input').serializeArray();
Console log for yellow_flags_ser is :
[Object, Object, Object, Object]
0: Object
name: "happens"
value: "injury"
__proto__: Object
1: Object
name: "should"
value: "call nurse"
__proto__: Object
2: Object
name: "happens"
value: "burn"
__proto__: Object
3: Object
name: "should"
value: "see doctor"
__proto__: Object
length: 4
__proto__: Array[0]
我想像JSON
[{happens_value : should_value}, {happens_value : should_value},...]
字符串
有人可以指导如何实现以上array of objects.
答案 0 :(得分:1)
您需要执行以下两个步骤: -
您需要在每对中跟踪count
,并在创建新对时,然后使用类/ ID附加该计数。
获取textareas
的所有值并准备JSON
对象
示例JS代码: -
var count = 1;
$('#addAnswerChoices').click(function(e){
count += 1;
$('<td class="answer_choice_'+count+'" >
<span style="float:left; font-size: 14px;">If This Happens...</span>
<textarea rows="2" cols="20" name="happens" style="float:left;" class="answer_choice_'+count+'" id="answer_choice_'+count+'" value=""
></textarea>
<span style="float:left; font-size: 14px;">I Should...</span>
<textarea rows="2" cols="20" name="should" style="float:left;" class="answer_choice_'+count+'" id="answer_choice_'+count+'" value=""
></textarea></td>').appendTo('#addAnswerChoices');
});
然后使用JQuery获取所有值并准备JSON
oject你想要的东西。 :)