我不确定我的标题是否正确,但我目前有一个可重复的表单,它可以将 JSON 字符串化,另一个正常的输入会将 JSON 字符串化,所以当点击克隆时,第二个输入被克隆,当点击提交时我在控制台中获取以下值是:
{"dependant1":[{"name":"daniel"}],"dependant2":[{"name":"allen"}]}
{"mainmember":[{"name":"steve"}]}
我怎样才能将两者结合起来得到:
{"mainmember": [{"name": "steve"}],"dependant1": [{"name": "daniel"}],"dependant2": [{"name": "allen"}]}
这是一个 jsFiddle:http: //jsfiddle.net/dawidvdh/uhJ7w/
和代码:
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var input_groups = ["group-1"];
var group;
var name_input_groups = ["name-group-1"];
var values;
var name_fields=[0];
var name_input = "<input class='name' name='name' type='text' />";
jQuery(document).ready(function(e) {
jQuery(name_fields).each(function() {
jQuery(name_input).appendTo('#name-group-1');
});
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
var oldId = g_counter;
g_counter++;
var id_newDiv = 'group-'+ g_counter;
currentdep ='dependant-'+g_counter;
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var name_newDiv = 'name-group-'+ g_counter;
$clonedDiv.find('#name-group-1').attr('id',"name-group-" + g_counter );
$clonedDiv.find('input[type="text"]').val('');
$clonedDiv.insertAfter("#dependant-" + oldId);
name_input_groups.push(name_newDiv);
input_groups.push(id_newDiv);
}
var result = {};
var dependants;
var mainmember;
var main_result = {};
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['name'] = $(v).find('.name').val();
});
jQuery('.main-member').each(function(k, v){
mainmember = {}
mainmember['name'] = $(v).find('.main_name').val();
main_result['mainmember'] = [mainmember];
});
var jsonData = JSON.stringify(result);
var mainData = JSON.stringify(main_result);
console.log(jsonData);
console.log(mainData);
jQuery.ajax({
type: "POST",
url: "mail.php",
dataType: "json",
data: {parameters: jsonData}
});
});
//submit function
});
然后是html
<div id="main-member" class="main-member">
<div id="label">full name:</div> <input class="main_name" />
</div>
<div id="dependant-1" class="dependant">
<div id="label">full name:</div> <div id="name-group-1"></div>
</div>
<button id="clone">Add a Dependant</button>
<button id="submit">submit</button>
而且他们必须在那里拥有自己的每个循环才能与其余代码一起工作。
提前致谢 :)。