Para esse efeito pode-se construir um número no exterior da função:
let num = 1;
E utilizar dentro dela e ir aumentando o mesmo. Depois pode-se concatenar esse número diretamente no html construído com:
cols += '<td ... name="product' + num + '"></td>';
Juntando tudo:
RemoveTableRow = function(handler) {
var tr = $(handler).closest('tr');
tr.fadeOut(400, function() {
tr.remove();
});
return false;
};
let num = 1; //num criado aqui
AddTableRow = function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td class="col-md-4"><input type="text" class="form-control product" name="product' + num + '"></td>';
cols += '<td class="col-md-2"><input type="text" class="form-control amount" name="amount' + num + '"></td>';
cols += '<td class="col-md-2"><input type="text" class="form-control price" name="price' + num + '"></td>';
cols += '<td class="col-md-2 total"><input readonly type="text" class="form-control" name="total' + num + '"></td>';
cols += '<td class="col-md-2">';
cols += '<a onclick="RemoveTableRow(this)" type="button"><i class="zmdi zmdi-delete zmdi-hc-lg"></i></a>';
cols += '</td>';
num++; //numero aumenta aqui
newRow.append(cols);
$("#products-table").append(newRow);
$(".amount, .price").unbind('blur keyup');
$(".amount, .price").on("blur keyup",function(){
const tr = $(this).parent().parent();
const quant = parseInt(tr.find('.amount').val());
const valor = parseInt(tr.find('.price').val());
var total = quant * valor;
if (!isNaN(quant) && !isNaN(valor)){
tr.find('.total').html('<input readonly type="text" class="form-control" name="total" value=" '+total+' ">');
}
});
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table m-0" id="products-table">
<thead>
<tr>
<th>Produto/Serviço</th>
<th>Quantidade</th>
<th>Valor Unitário</th>
<th>Valor Total</th>
<th>Remover</th>
</tr>
</thead>
<tbody class="row">
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<button class="btn btn-info waves-effect w-md waves-light m-b-5" onclick="AddTableRow()" type="button">Adicionar Produto</button>
</td>
</tr>
</tfoot>
</script>
Esta solução garante que cada name
é único mas não garante que é estritamente sequencial se forem entretanto removidas linhas no meio. Para garantir que ficam sequenciais, caso seja uma imposição do problema será necessário elaborar um pouco. Para isso podemos re-atribuir toda a numeração sempre que é inserida ou eliminada uma linha da tabela:
function ajustarNomes(){
$(".table tr").each(function(indice){
$(this).find('.product').attr("name", "product" + indice);
$(this).find('.amount').attr("name", "amount" + indice);
$(this).find('.price').attr("name", "price" + indice);
$(this).find('.total').attr("name", "total" + indice);
});
}
E agora chamar esta função cada vez que se insere ou remove linhas.
function ajustarNomes(){
$(".table tr").each(function(indice){
//acha cada elemento de cada <tr> e coloca o name correto de acordo com o indice
$(this).find('.product').attr("name", "product" + indice);
$(this).find('.amount').attr("name", "amount" + indice);
$(this).find('.price').attr("name", "price" + indice);
$(this).find('.total').attr("name", "total" + indice);
});
}
RemoveTableRow = function(handler) {
var tr = $(handler).closest('tr');
tr.fadeOut(400, function() {
tr.remove();
});
ajustarNomes();
return false;
};
AddTableRow = function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td class="col-md-4"><input type="text" class="form-control product" name="product"></td>';
cols += '<td class="col-md-2"><input type="text" class="form-control amount" name="amount"></td>';
cols += '<td class="col-md-2"><input type="text" class="form-control price" name="price"></td>';
cols += '<td class="col-md-2 total"><input readonly type="text" class="form-control" name="total"></td>';
cols += '<td class="col-md-2">';
cols += '<a onclick="RemoveTableRow(this)" type="button"><i class="zmdi zmdi-delete zmdi-hc-lg"></i></a>';
cols += '</td>';
newRow.append(cols);
$("#products-table").append(newRow);
$(".amount, .price").unbind('blur keyup');
$(".amount, .price").on("blur keyup",function(){
const tr = $(this).parent().parent();
const quant = parseInt(tr.find('.amount').val());
const valor = parseInt(tr.find('.price').val());
var total = quant * valor;
if (!isNaN(quant) && !isNaN(valor)){
tr.find('.total').html('<input readonly type="text" class="form-control" name="total" value=" '+total+' ">');
}
});
ajustarNomes();
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table m-0" id="products-table">
<thead>
<tr>
<th>Produto/Serviço</th>
<th>Quantidade</th>
<th>Valor Unitário</th>
<th>Valor Total</th>
<th>Remover</th>
</tr>
</thead>
<tbody class="row">
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: left;">
<button class="btn btn-info waves-effect w-md waves-light m-b-5" onclick="AddTableRow()" type="button">Adicionar Produto</button>
</td>
</tr>
</tfoot>
</script>