Real-time account for table generated with jQuery

4

I'm having trouble letting the multiplication of quantity * price in a dynamically created table.

Better to explain, is to show. Here is the code in jsfiddle: link

HTML

<div class="container">
                <div class="row">
                    <h3>Produtos</h3>
                    <table id="details-table" class="table">
                        <tbody>
                            <tr>
                                <th scope="col" class="col-1">Item</th>
                                <th scope="col" class="col-5">Produto</th>
                                <th scope="col" class="col-1">Quantidade</th>
                                <th scope="col" class="col-2">Preço</th> 
                                <th scope="col" class="col-3">Total</th>                                
                            </tr>
                        </tbody>
                    </table>
                </div>
                <!-- #detail-details -->
                <div class="form-group">
                    <button class="btn btn-primary" type="button" id="btn-add-item">Novo Item</button>
                    <input class="btn btn-success" type="submit" value="Salvar">
                </div>
            </div>

jQuery

(function ($) {

    var counter = 0;

    addRow = function () {

        var table = $('#details-table');
        var input = null;

        var row = $('<tr class="linha">');
        var cols = [];

        counter++;

        // Coluna 1 - Item
        input = $('<input>').addClass('form-control').attr('name', 'item' + counter + '').val(counter).attr('disabled', 'disabled');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 2 - Produto
        input = $('<input>').addClass('form-control').attr('name', 'produto' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 3 - Quantidade
        input = $('<input>').addClass('form-control').attr('name', 'quantidade' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 4 - Preço
        input = $('<input>').addClass('form-control').attr('name', 'preco' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 5 - Total
        input = $('<input>').addClass('form-control').addClass('total').attr('name', 'total' + counter + '').val(totalPreco).attr('disabled', 'disabled');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Button Remove
        cols.push(
            $('<td>').addClass('actions').append(
                $('<button>').addClass('btn btn-danger btn-remove-item').html('&times;').attr('type', 'button').on('click', removeRow)
            )
        );

        row.append(cols);
        table.append(row);

        return false;
    }

    totalPreco = function () {
        $('input[name="total'+counter+'"]').on('keyup', function(){
            var quantidade = $('input[name="quantidade'+counter+'"]').val();
            var preco = $('input[name="preco'+counter+'"]').val()
            var total = $('input[name="total'+counter+'"]');
            var precoTotal = parseFloat(quantidade) * parseFloat(preco);
            return precoTotal;
        });
    }

    removeRow = function () {

        $(this).closest('.linha').remove();
        return false;
    }

    $('#btn-add-item').click(addRow);
})(jQuery);

Thanks in advance!

    
asked by anonymous 18.12.2017 / 23:08

2 answers

1

You can create a listener in the fields quantidade of preço which will send the result of the multiplication to the total field as values are entered:

$("#details-table").on("input","input.form-control",function(){
   var linha = $(this).closest("tr");
   var calcula = parseFloat(linha.find("input[name*=quantidade]").val()) * parseFloat(linha.find("input[name*=preco]").val());
   linha.find("input[name*=total]").val( isNaN(calcula) ? '' : calcula);
});

See:

(function ($) {

    var counter = 0;

    addRow = function () {

        var table = $('#details-table');
        var input = null;

        var row = $('<tr class="linha">');
        var cols = [];

        counter++;

        // Coluna 1 - Item
        input = $('<input>').addClass('form-control').attr('name', 'item' + counter + '').val(counter).attr('disabled', 'disabled');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 2 - Produto
        input = $('<input>').addClass('form-control').attr('name', 'produto' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 3 - Quantidade
        input = $('<input>').addClass('form-control').attr('name', 'quantidade' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 4 - Preço
        input = $('<input>').addClass('form-control').attr('name', 'preco' + counter + '');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Coluna 5 - Total
        input = $('<input>').addClass('form-control').addClass('total').attr('name', 'total' + counter + '').val(totalPreco).attr('disabled', 'disabled');
        cols.push(
            $('<td>').append(
                $('<div>').addClass('form-group').append(input)
            )
        );

        // Button Remove
        cols.push(
            $('<td>').addClass('actions').append(
                $('<button>').addClass('btn btn-danger btn-remove-item').html('&times;').attr('type', 'button').on('click', removeRow)
            )
        );

        row.append(cols);
        table.append(row);

        return false;
    }

    totalPreco = function () {
        $('input[name="total'+counter+'"]').on('keyup', function(){
            var quantidade = $('input[name="quantidade'+counter+'"]').val();
            var preco = $('input[name="preco'+counter+'"]').val()
            var total = $('input[name="total'+counter+'"]');
            var precoTotal = parseFloat(quantidade) * parseFloat(preco);
            return precoTotal;
        });
    }

    removeRow = function () {

        $(this).closest('.linha').remove();
        return false;
    }

    $('#btn-add-item').click(addRow);
})(jQuery);

$("#details-table").on("input","input.form-control",function(){
   var linha = $(this).closest("tr");
   var calcula = parseFloat(linha.find("input[name*=quantidade]").val()) * parseFloat(linha.find("input[name*=preco]").val());
   linha.find("input[name*=total]").val( isNaN(calcula) ? '' : calcula);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="container">
    <div class="row">
        <h3>Produtos</h3>
        <table id="details-table" class="table">
            <tbody>
                <tr>
                    <th scope="col" class="col-1">Item</th>
                    <th scope="col" class="col-5">Produto</th>
                    <th scope="col" class="col-1">Quantidade</th>
                    <th scope="col" class="col-2">Preço</th> 
                    <th scope="col" class="col-3">Total</th>                                
                </tr>
            </tbody>
        </table>
    </div>
    <!-- #detail-details -->
    <div class="form-group">
        <button class="btn btn-primary" type="button" id="btn-add-item">Novo Item</button>
        <input class="btn btn-success" type="submit" value="Salvar">
    </div>
</div>

Edit

If you want the value in total formatted in cents:

$("#details-table").on("input","input.form-control",function(){

   var linha = $(this).closest("tr");

   var i_qtd = parseFloat(linha.find("input[name*=quantidade]").val());
   var i_preco = parseFloat(linha.find("input[name*=preco]").val().replace(',','.'));

   var calcula = i_qtd * i_preco;
   linha.find("input[name*=total]").val( isNaN(calcula) ? '' : calcula.toFixed(2).replace('.',','));
});
    
18.12.2017 / 23:38
1

The code was using what was with a change in the part of the calculation, then add a plugin so that in input let enter number with comma (jquery.numeric ), and in input quantity and price in evento of blur is checked if entered in the two boxes and if the multiplication calculation is done, for example:

(function($) {

  var counter = 0;

  addRow = function() {

    var table = $('#details-table');
    var input = null;

    var row = $('<tr class="linha">');
    var cols = [];

    counter++;

    // Coluna 1 - Item
    input = $('<input>').addClass('form-control').attr('name', 'item' + counter + '').val(counter).attr('disabled', 'disabled');
    cols.push(
      $('<td>').append(
        $('<div>').addClass('form-group').append(input)
      )
    );

    // Coluna 2 - Produto
    input = $('<input>').addClass('form-control').attr('name', 'produto' + counter + '');
    cols.push(
      $('<td>').append(
        $('<div>').addClass('form-group').append(input)
      )
    );

    // Coluna 3 - Quantidade
    input = $('<input>').addClass('form-control').attr('name', 'quantidade' + counter + '').attr('id', 'quantidade' + counter).blur(function() {
      return totalPreco(this);
    }).numeric();
    cols.push(
      $('<td>').append(
        $('<div>').addClass('form-group').append(input)
      )
    );

    // Coluna 4 - Preço
    input = $('<input>').addClass('form-control').attr('name', 'preco' + counter + '').attr('id', 'preco' + counter).blur(function() {
      return totalPreco(this);
    }).numeric();
    cols.push(
      $('<td>').append(
        $('<div>').addClass('form-group').append(input)
      )
    );

    // Coluna 5 - Total
    input = $('<input>').addClass('form-control').addClass('total').attr('name', 'total' + counter + '').attr('id', 'total' + counter + '').attr('disabled', 'disabled');
    cols.push(
      $('<td>').append(
        $('<div>').addClass('form-group').append(input)
      )
    );

    // Button Remove
    cols.push(
      $('<td>').addClass('actions').append(
        $('<button>').addClass('btn btn-danger btn-remove-item').html('&times;').attr('type', 'button').on('click', removeRow)
      )
    );

    row.append(cols);
    table.append(row);

    return false;
  }

  totalPreco = function(obj) {
    var id = obj.id.replace(/[^0-9]/g, '')
    var p = $("#preco" + id).val();
    var q = $("#quantidade" + id).val();
    if (p && q) {
      var c = (parseFloat(p.replace(',','.')) * parseFloat(q.replace(',','.')));
      $("#total" + id).val(isNaN(c) ?'':c.toFixed(2).replace('.',','));
    }

  }

  removeRow = function() {

    $(this).closest('.linha').remove();
    return false;
  }

  $('#btn-add-item').click(addRow);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.alphanum/1.0.24/jquery.alphanum.js"></script>

<div class="container">
  <div class="row">
    <h3>Produtos</h3>
    <table id="details-table" class="table">
      <tbody>
        <tr>
          <th scope="col" class="col-1">Item</th>
          <th scope="col" class="col-5">Produto</th>
          <th scope="col" class="col-1">Quantidade</th>
          <th scope="col" class="col-2">Preço</th>
          <th scope="col" class="col-3">Total</th>
        </tr>
      </tbody>
    </table>
  </div>
  <!-- #detail-details -->
  <div class="form-group">
    <button class="btn btn-primary" type="button" id="btn-add-item">Novo Item</button>
    <input class="btn btn-success" type="submit" value="Salvar">
  </div>
</div>
    
19.12.2017 / 00:05