Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何增加html输入名称_Javascript_Jquery_Html_Ruby On Rails - Fatal编程技术网

Javascript 如何增加html输入名称

Javascript 如何增加html输入名称,javascript,jquery,html,ruby-on-rails,Javascript,Jquery,Html,Ruby On Rails,如何在放入jQuery.after()的html名称“”中增加数组 像这样 $(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=

如何在放入jQuery.after()的html名称“”中增加数组

像这样

$(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>');
    });
  });
$(文档).ready(函数(){
$(“#添加产品”)。单击(函数(){
$('.products_tr:last')。在('')之后;
});
});
它应该向发票中添加额外的行,并且可以正常工作,但为了将其正确保存到数据库中,
name=“invoice[products\u attributes][1][quantity]
中的“[1]”需要递增。它需要基于上一个值递增

顺便说一句,该代码是由RubyonRails动态创建的

有人知道实现这一点的方法吗?非常感谢您的帮助!

获取总行数(因为索引从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>');
   });
 });
$(文档).ready(函数(){
$(“#添加产品”)。单击(函数(){
l=$('.products_tr').length;//以获取总计
$('.products_tr:last')。在('')之后;
});
});
正如@Pete所评论的,如果您有一个delete按钮,那么使用一个全局变量并像这样递增

$(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++;
   });
 });
$(文档).ready(函数(){
var counter=$('.products_tr').length;//最初它等于所有行的长度,让它从0开始
$(“#添加产品”)。单击(函数(){
$('.products_tr:last')。在('')之后;
计数器++;
});
});

“…name=”发票[products_attributes]['+a value+'…”
唯一的问题是,如果有一个“删除行”按钮,那么在重试后,它实际上不起作用,因为它没有超过[1]。当我添加第三行时,它保持在[1]上。哦,是的,我的错误,对不起,我弄乱了计数器++;