0

Tenho uma tabela que gera linhas ao clicar em um botão. Nessas linhas tem dois inputs (amount e price) que preciso pegar os valores inseridos, multiplicar e o resultado exibir em uma coluna de total quando o usuario clicar fora do input estando os dois preenchidos. Não estou sabendo como fazer essa multiplicação e exibir o resultado.

<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>
2
  • Podes explicar a conta que queres fazer e como ela é iniciada? clicando em que botão?
    – Sergio
    30/07/2017 às 5:31
  • É apenas uma multiplicação entre o campo amount (quantidade) e price (preço) e o resultado na coluna total. Não teria botão, o resultado apareceria ao clicar fora dos iinputs, estando os dois preenchidos.
    – Marcelo
    30/07/2017 às 12:18

2 Respostas 2

2

Neste exemplo o resultado é formatado para o padrão pt-BR com duas casas decimais

$(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>
  <table class="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>

2
  • A resposta do Isac executou normalmente a função de remover no chrome. Mas obrigado pela resposta.
    – Marcelo
    30/07/2017 às 18:11
  • @Marcelo, uso Firefox e na resposta do Isac não aparece o remover, nessa daqui do aparece.
    – user76097
    16/09/2018 às 12:06
1

Para responder a essa lógica pode-se criar uma função para os dois eventos, o de blur (clicar fora) e keyup no momento em que se adiciona uma nova linha, e para os elementos adicionados. Essa função apenas tem que navegar no html da linha construída para ir buscar o amount e price com base na função find e fazer os cálculos apropriados:

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

Desta forma as funções que antes existiam para cálculo dos totais já não são necessárias.

Colocando tudo a funcionar:

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

1
  • Funcionou perfeito. Obrigado.
    – Marcelo
    30/07/2017 às 13:37

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .