【问题标题】:How to increment html input name如何增加html输入名称
【发布时间】:2016-08-24 10:40:10
【问题描述】:

如何在 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 动态创建的。

有人知道实现此目的的方法吗?帮助将不胜感激!

【问题讨论】:

  • '...name="invoice[products_attributes]['+ a value+'...'

标签: javascript jquery html ruby-on-rails


【解决方案1】:

获取总行数(因为索引从 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++;
   });
 });

【讨论】:

  • 唯一的问题是如果也有删除行按钮
  • 其实重试后还是不行,因为没有通过[1]。当我添加第三行时,它会停留在 [1] 上。
  • 哦,是的,我的错误,对不起,我把柜台弄乱了++;
猜你喜欢
  • 2017-05-21
  • 1970-01-01
  • 2015-05-23
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
  • 2013-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多