我如何在 jQuery .after() 中的 html name=""中递增数组?
像这样
$(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 动态创建的。
有人知道实现这个的方法吗?帮助将不胜感激!
最佳答案
获取总行数(因为索引从 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++;
});
});
关于javascript - 如何增加html输入名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39121030/