我有一个带有动态输入的表格。输入具有相同的名称属性。所以我想为每一行制作数组。
赞!
[{'company':'Apple'},{'address':'USA'}],
[{'company':'Samsung'},{'address':'Korea'}]
我正在使用此简单表单(动态);
<form id='companies'>
<input name='company[]'>
<input name='address[]'>
</form>
还有这个
$('form').submit(function(event) {
var newFormData = $('#companies').serializeArray();
console.log(newFormData);
event.preventDefault();
});
控制台日志; (所有输入都在同一数组中)
[{'company':'Apple'},{'address':'USA'},{'company':'Samsung'},{'address':'Korea'}]
答案 0 :(得分:1)
这是解决问题的一个示例:)
<form id='companies'>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
<div class='container-input'>
<input name='company[]'>
<input name='address[]'>
</div>
... -> Now you have dynamic containers
</form>
您可以使用这种方法来解决jQuery的问题。
$('#companies').submit(function(event) {
var $data = [];
var $containers = $(".container-input");
$containers.each(function() {
var $contenedor = $(this);
var $inputCompany = $contenedor.find('input[name^="company"]');
var $inputAddress = $contenedor.find('input[name^="address"]');
var $objectInput = [{
'company': $inputCompany.val()
}, {
'address': $inputAddress.val()
}];
$data.push($objectInput);
});
console.log($data);
});
答案 1 :(得分:0)
可以帮助:)更动态。
$('#companies').submit(function(event) {
var $data = [];
$.each($(this).children("div"),function(){
obj={};
$.each($(this).find(":input"),function(){
obj[$(this).attr("name").replace("[]","")]=$(this).val();
$data.push(obj);
});
})
console.log($data);
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='companies'>
<div class="input">
<input name='company[]'>
<input name='address[]'>
<input name='phone[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<div class="input">
<input name='company[]'>
<input name='address[]'>
</div>
<input type="submit"/>
</form>