Multiply dynamic input values

Asked

Viewed 1,674 times

0

I have a table that generates lines by clicking a button. In these lines there are two inputs (amount and price) that need to take the entered values, multiply and the result display in a column of total when the user click out of the input being both 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>
  • Can you explain the account you want to do and how it starts? by clicking on which button?

  • It is just a multiplication between the amount (quantity) and price (price) field and the result in the total column. There would be no button, the result would appear when clicking outside the iinputs, with both filled.

2 answers

2

In this example the result is formatted to default pt-BR to 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>
  <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>

  • The Isac response normally performed the remove function on Chrome. But thanks for the answer.

  • @Marcelo, use Firefox and in the Isac response does not appear to remove, this from appears.

1


To respond to this logic one can create a function for the two events, the blur (click out) and keyup when adding a new line, and for the added elements. This function only has to navigate the html of the line built to fetch the amount and price based on function find and make 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
    }
});

Thus the functions that previously existed for calculating 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>
<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>

  • It worked perfect. Thank you.

Browser other questions tagged

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