我正忙于表单重复,当按下提交时,我希望它以以下格式解析为 json:
{ "dependant1": [
{ "name": "daniel"},
],"dependant2": [
{ "name": "steve"},
]
}
对于每个添加的依赖项,目前,如果我添加多个依赖项,则返回“{} {}”,但如果只有一个依赖项,则返回“{“name”:“steve”}。
非常感谢任何帮助。继承人的代码:
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var name_input_groups = ["name-group-1"];
//General Variables
//Generate variables
var name_fields=[0];
var name_input = "<input class='name' />";
//Generate variables
jQuery(document).ready(function(e) {
jQuery(name_fields).each(function() {
jQuery(name_input).appendTo('#name-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var name_newDiv = 'name-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#name-group-1').attr('id',"name-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
name_input_groups.push(name_newDiv);
};
//Cloning Function
function validate_gen() {};
//submit function
var dep_counter = 0
jQuery('#submit').click(function(){
$('.dependant').each(function(k, v){
dep_counter++;
var dependants = {};
dependants['name'] = jQuery("#name-group-" + dep_counter).find('input').val();
var json = JSON.stringify(dependants);
console.log(json);
});
});
});
和继承人的HTML:
<div id="dependant-1" class="dependant">
name<div id="name-group-1"></div>
</div>
<div id="test"></div>
<button id="clone">clone</button>
<button id="submit">submit</button>
和 jsFiddle 链接 - http://jsfiddle.net/dawidvdh/TzRu8/2/
谢谢。