我想在javascript中获取一个Object,其中包含来自我动态生成的数组的值,所以稍后我将能够对该对象进行jsonencode并将其保存到我的数据库中。 (也许有一种更简单的方法)
这是表格
<form name="second_form" id="second_form" action="#" method="POST">
<a href="#" id="AddChampion" onclick="return false;">Add Champion</a>
<div id="ChampionInput">
</div>
<input type="submit" name="submit">
</form>
以下是我用来创建此数组的函数:
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<input type="text" class="ChampionInput">\
<a href="#" class="AddGeneralChange">Add General Change</a>\
<div class="GeneralChanges">\
</div>\
<div>');
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" class="GeneralChangeDescription"></textarea>\
</div>');
});
以下是我尝试过没有结果的内容。我试图遍历我的数组的值,然后把它放到一个对象中,我得到整个div而不是实际值。
$( "#second_form" ).submit( function(event) {
$( "#ChampionInput.ChampionInput :input" ).each( function( index, value ) {
var _value = value;
var _index = index;
alert(value);
$(this).children( ".GeneralChangeDescription").each( function( index, value ) {
});
});
});
以下是添加一些字段http://imgur.com/QXhWSHA
后的图片这里有jSfiddle:http://jsfiddle.net/ss84agxv/
答案 0 :(得分:0)
试试这段代码,我希望我能正确理解你的问题。
$("#second_form").submit(function(event) {
//don't do the default action on submit
event.preventDefault();
//Your object as array for the champions
var object = [];
//Loop through each .Champion-div
$('.Champion').each(function() {
//Create a new object for this champion with the value from the input field and an array for the descriptions
var champion = {
'name': $(this).find(".ChampionInput").val(),
'description': []
};
//Loop through each description textfields of this champion
$(this).find('.GeneralChangeDescription').each(function() {
//add the description to the description array of the champion
champion.description.push($(this).val());
});
//finally put the champion in your champion array
object.push(champion);
});
//Thats just for you, an alert of the json-object
alert(JSON.stringify(object));
});