Increment dynamic input name with jquery

Asked

Viewed 548 times

2

I have a table that generates the line dynamically by clicking a button. I need the 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 I make this increment? I tried to use split to get a value placed the first time the button is clicked but only manage to 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>

1 answer

3


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

let num = 1;

And use it inside 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>
<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>

This solution ensures that each name is unique but does not guarantee that it is strictly sequential if lines are removed in the middle. To ensure that they remain sequential, if a problem is imposed it will be necessary to elaborate a little. 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 every time it inserts or removes lines.

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>

  • What’s the difference in putting Let in one instead of var in one?

  • @Marcelo The difference is in the scope of the variable, which with var is relative to the function or the window whereas in let is local to the keypad where it was declared, similar to a normal variable as in other languages. There are also other subtleties for the let but for the above code there is no difference and could have been defined as var, was same matter of habit. I also advise to read the documentation of the et if you have doubts

  • It worked. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.