当我尝试查看所有输入值时,它总是显示最后一个。
function addInput() {
$('.addElement').append('<label>Sağlık Etkisi</label><input id="health" name="health[]" type="text" class="form-control message">');
$('.addElement').append('<label>Yaşam Tarzı Önerisi</label><input id="lifeStyle" name="lifeStyle[]" type="text" class="form-control message">');
$('.addElement').append('<label>Öneriler</label><input id="advice" name="advice[]" type="text" class="form-control message">');
}
我正在向表单添加 3 个输入。
$('#test').submit(function(e) {
e.preventDefault();
var text = [];
$("input[name='health[]']").each(function(index, item) {
text['health'] = item.value;
});
$("input[name='lifeStyle[]']").each(function(index, item) {
text["lifeStyle"] = item.value;
});
$("input[name='advice[]']").each(function(index, item) {
text["advice"] = item.value;
});
我做了text[index]['health']
,这也给了我错误。
这个输出代码,总是给我最后 3 个输入值。 对不起我的英语。
最佳答案
问题是因为您在每次迭代中都覆盖了 health
、lifeStyle
和 advice
属性的值,因此在最终每个循环中的值都是可访问的。
解决此问题的一种解决方案是构建输入值数组并将其分配给属性:
$('#test').submit(function(e) {
e.preventDefault();
var healthVals = $("input[name='health[]']").map(function() { return this.value; }).get();
var lifestyleVals = $("input[name='lifeStyle[]']").map(function() { return this.value; }).get();
var adviceVals = $("input[name='advice[]']").map(function() { return this.value; }).get();
var text = [];
text['health'] = healthVals;
text['lifeStyle'] = lifestyleVals;
text['advice'] = adviceVals;
});
另请注意,循环附加元素的事实意味着它们可以有多个副本。在这种情况下,您应该从附加的 HTML 中删除 id
属性,因为这会导致无效的重复。
关于javascript - 无法将所有数组键和值放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481809/