Increment dynamic input name with jquery

1

I have a table that generates the row dynamically when I click a button. I need names to be incremented when generating a new line. Ex: name="product1" name="amount1" name="price1" name="total1" changing only the number (1, 2, 3 ...) How could you make this increase? I tried to use split to get a value placed the first time the button was clicked but could only increment once.

<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>

Jquery

<script>

RemoveTableRow = function(handler) {
    var tr = $(handler).closest('tr');
    tr.fadeOut(400, function() {
        tr.remove();
    });
    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+' ">');
        }
    });

    return false;
};

</script>
    
asked by anonymous 30.07.2017 / 18:55

1 answer

2

For this purpose you can construct a number outside the function:

let num = 1;

And use within it and increase it. Then you can concatenate this number directly into the html built with:

cols += '<td ... name="product' + num + '"></td>';

Putting it all together:

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><tableclass="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>

This solution ensures that each name is unique but does not guarantee that it is strictly sequential if lines are removed in the meanwhile. To ensure that they are sequential, if it is an imposition of the problem will need to elaborate a bit. For this we can re-assign all numbering whenever a table row is inserted or deleted:

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);
    });
}

And now call this function each time you insert or remove rows.

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><tableclass="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>
    
30.07.2017 / 19:06