luissimo luissimo - 3 months ago 11
HTML Question

How to increment html input name

how can i increment an array inside a html name="" that is put inside a jQuery .after()?

Like this

$(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>');
});
});


It's supposed to add extra rows to a invoice, and its working but in order to save it correctly to the database the '[1]' inside
name="invoice[products_attributes][1][quantity]
needs to increment. And it needs to increment based on the last value.

That code is dynamically created by Ruby On Rails btw.

Anybody know a way to accomplish this? Help would be appreciated!

Answer

Get the total rows(as index start from 0 so no need to add 1) to it so that you will get new index for the newly generated row and use class="quantity" as id must be unique,

$(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>');
   });
 });
Comments