如何在html name =“”中增加一个数组,该数组放在jQuery .after()中?
喜欢这个
$(document).ready(function() {
$('#add_products').click(function() {
$('.products_tr:last').after('<tr class="products_tr"><td><input id="quantity" class="form-control" type="text" value="" name="invoice[products_attributes][1][quantity]"></td></tr>');
});
});
应该在发票中添加额外的行,并且它的工作正常但为了将其正确保存到数据库中,name="invoice[products_attributes][1][quantity]
内的“[1]”需要递增。它需要根据最后一个值递增。
该代码由Ruby On Rails btw动态创建。
有人知道实现这个目标的方法吗?帮助将不胜感激!
答案 0 :(得分:3)
获取总行数(因为索引从0开始,因此无需添加1),以便为新生成的行获取新索引并使用class="quantity"
,因为id
必须是唯一的,
$(document).ready(function() {
$('#add_products').click(function() {
l=$('.products_tr').length;// to get total
$('.products_tr:last').after('<tr class="products_tr"><td><input '+
' class="quantity" class="form-control" type="text" value="" '+
' name="invoice[products_attributes]['+l+'][quantity]"></td></tr>');
});
});
正如@Pete所评论的,如果你有一个删除按钮,那么使用一个全局变量并将其增加,如,
$(document).ready(function() {
var counter = $('.products_tr').length; // initially it is equal to length of all rows, let it start from 0
$('#add_products').click(function() {
$('.products_tr:last').after('<tr class="products_tr"><td><input '+
' class="quantity" class="form-control" type="text" value="" '+
' name="invoice[products_attributes]['+counter+'][quantity]"></td></tr>');
counter++;
});
});