[英]Creating an object from dynamic HTML array
I want to get an Object in javascript with values from my dynamically generated array in correct order so then later on I will be able to jsonencode that object and save it into my Database. 我想用正确顺序从动态生成的数组中获取值的javascript中的对象,这样以后我就可以对该对象进行jsonencode并将其保存到我的数据库中。 (Maybe there is a different easier way of doing it)
(也许有另一种更简单的方法)
Here is the form 这是表格
<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>
Here are functions that I use to create this array: 这是我用来创建此数组的函数:
$('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>');
});
And below is what I've tried with no result. 下面是我尝试的结果,没有结果。 I was trying to loop through values of my array and then put it into an object I get the whole div instead of the actual value.
我试图遍历数组的值,然后将其放入对象中,但得到的是整个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 ) {
});
});
});
Here is a picture of how it could look like after adding some fields http://imgur.com/QXhWSHA 这是添加一些字段后的外观图片http://imgur.com/QXhWSHA
And here is working jSfiddle: http://jsfiddle.net/ss84agxv/ 这是正在工作的jSfiddle: http : //jsfiddle.net/ss84agxv/
Try this code, I hope that I understood your question correctly. 尝试这段代码,希望我能正确理解您的问题。
$("#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));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.