Real-time account for table generated with jQuery

Asked

Viewed 150 times

4

I’m having trouble leaving the quantity * price multiplication in a dynamically created table.

Better than explaining, it’s showing. Follow the code in jsfiddle: https://jsfiddle.net/koew1s75/

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

2 answers

1


You can create a Listener in the fields quantidade of preço that will send the multiplication result to the field total 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);
});

Behold:

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

Edit

If you want the total pennies:

$("#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('.',','));
});
  • Hmm perfect, that’s exactly what I was trying to do, define it as this. Thanks!

  • @Develop_sp Thanks man! Gave a little improved code. Abs!

1

The code was using what was with a change in the calculation part, then add a plugin so that in the input Let me type number with comma (jquery.Numeric), and in the input amount and price in the evento of blur is checked if it was typed in the two boxes and if yes is done the multiplication calculation, 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><script src="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>

Browser other questions tagged

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