Multiplying value of dynamic inputs

0

I have a table that generates rows when I click a button. In these lines there are two inputs (amount and price) that I need to get the values entered, multiply and the result display in a total column when the user clicks out of the input while the two are filled. I'm not sure how to do this multiplication and display the result.

<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

<script>

function amount(value) {
    var amount = value;
    return amount;
}

function price(value) {
    var price = value;
    return price;
}

function total(amount, price) {
    total = amount * price;
}

$(document).ready(function() {

    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[]" onkeyup="amount(this.value)"></td>';
        cols += '<td class="col-md-2"><input type="text" class="form-control price" name="price[]" onkeyup="price(this.value)"></td>';
        cols += '<td class="col-md-2 total">R$ 100,00</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);

        return false;
    };

});
</script>
    
asked by anonymous 30.07.2017 / 05:03

2 answers

1

In order to respond to this logic you can create a function for the two events, the blur (click away) and keyup at the moment a new row is added, and for the added elements. This function only has to navigate the html of the built line to fetch the amount and price based on the find function and make the appropriate calculations:

$(".amount, .price").on("blur keyup",function(){ //register o evento de blur e keyup
    const tr = $(this).parent().parent(); //andar dois elementos para cima até ao <tr>

    const quant = parseInt(tr.find('.amount').val()); //ir buscar a quantidade com base no <tr>
    const valor = parseInt(tr.find('.price').val()); //ir buscar o valor com base no <tr>

    if (!isNaN(quant) && !isNaN(valor)){ //ver se ambos existem
      tr.find('.total').html("R$ " + (quant * valor)); //aplicar o calculo no total
    }
});

In this way the functions that previously existed to calculate the totals are no longer necessary.

Making it all work:

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">R$ 100,00</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());
    
    if (!isNaN(quant) && !isNaN(valor)){
      tr.find('.total').html("R$ " + (quant * valor));
    }
  });

  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>
    
30.07.2017 / 14:48
2

In this example, the result is formatted to the default pt-BR with two decimal places

$(document).ready(function () {
    var contador = 1;
    //adiciona nova linha
    $("#addLinha").on("click", function () {
        contador++;
        
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="text" name="produto' + contador + '"/></td>';
        cols += '<td><input type="text" name="preco' + contador + '"/></td>';
        cols += '<td><input type="text" name="quant' + contador + '"/></td>';
        cols += '<td class="col-md-2 total">R$ 100,00</td>';
        cols += '<td><a class="deleteLinha"> Excluir </a></td>';
        newRow.append(cols);
        
        $("#products-table").append(newRow);
    });
    
    //chamada da função para calcular o total de cada linha
    $("#products-table").on("blur keyup", 'input[name^="preco"], input[name^="quant"]', function (event) {
        calculateRow($(this).closest("tr"));
    });
    
    //remove linha
    $("#products-table").on("click", "a.deleteLinha", function (event) {
        $(this).closest("tr").remove();
    });
});
 
//função para calcular o total de cada linha   
function calculateRow(row) {
    var preco = +row.find('input[name^="preco"]').val();
    var quant = +row.find('input[name^="quant"]').val();
    //2 casas decimais
    var tot = (preco * quant).toFixed(2);
    //substitui ponto por virgula
    tot=tot.replace(".", ",");
    //a regex abaixo coloca um ponto a esquerda de cada grupo de 3 digitos desde que não seja no inicio do numero
    row.find('.total').html("R$ " + (tot).replace(/\B(?=(\d{3})+(?!\d))/g, "."));     
}
.deleteLinha { 
   color:blue;
   cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table m-0" classe="order-list" id="products-table">
    <thead>
      <tr>
      <th>Produto/Serviço</th>
      <th>Quantidade</th>
      <th>Valor Unitário</th>
      <th>Valor Total</th>
      </tr>
    </thead>
    
    <tbody class="row">

    </tbody>
    
    <tfoot>
    <tr>
      <td colspan="4" style="text-align: left;">
        <button class="btn btn-info waves-effect w-md waves-light m-b-5"  id="addLinha" type="button">Adicionar Produto</button>
      </td>
    </tr>
  </tfoot>    
</table>
    
30.07.2017 / 19:49