Perform mathematical calculations with values from a PivotTable

4

I have a table in form-wizard that as soon as I click on "add item" I call a function and it adds a row in the table to add a new item to be purchased by the client.

This table with each click adds an item has an autocomplete function in the "Title" field in which it searches the values of "Code", "Unit Value" and "Quantity available" in the database and automatically fills in these fields that are disabled as shown in the picture above.

The input "Quantity Sold" must be entered manually by the user.

Here is the image below the section quoted above:

BelowIhaveinputsthataddthediscountandanotherthatshouldshowthetotalvalueofthesalebasedontheaboveinformation.

Here'sapicture:

My problem is that I can not perform the calculation to know the total value. This calculation should be based on the unit value and quantity sold of each item.

If it were a static number of items I would know, but how every click on the "add item" button causes it to generate new values as I do to calculate the total value?

Function code that autocompletes and adds values to the inputs disabled:

<script id="teste" language="JavaScript" type="text/javascript">
$(function(){
    var cnt = 1;
    var quantidadedisponivel;     

$("#adicionar_item").click(function(){

    $('#tabela_publicacoes tr').last().after('<tr><td>'+cnt+'</td><td><input type="hidden" name="titulopublicacao'+cnt+'" id="titulopublicacao'+cnt+'" style="width: 500px;"></td><td><input class="form-control" name="cod_publicacao'+cnt+'" id="cod_publicacao'+cnt+'" type="text" disabled="disabled"></td><td><input class="form-control" disabled="disabled" name="valorunitario'+cnt+'" id="valorunitario'+cnt+'" type="text" value="0" onChange="Calcular_ValorTotal(this.form)"></td><td><input class="form-control" name="quantidadedisponivel'+cnt+'" id="quantidadedisponivel'+cnt+'" type="text" disabled="disabled" value=""></td><td><input class="form-control" name="quantidadevendida'+cnt+'" id="quantidadevendida'+cnt+'" type="text" value="0" onChange="Calcular_ValorTotal(this.form)"></td></tr>');      

        $('#titulopublicacao'+cnt).select2({
            placeholder: "Digite o título da Publicacao",
            ajax: {         
                url: 'autosuggest_busca_publicacao.php',
                dataType: 'json',
                quietMillis: 50,
                data: function (term) {
                    return {
                        term: term
                    };
                },
                results: function (data) {
                    var results = [];
                    $.each(data, function (index, item) {
                        results.push({
                            text: item.titulopublicacao + " - Número: " + item.numero + " - Ano: " + item.ano,
                            id: item.cod_publicacao,
                            cod_publicacao: item.cod_publicacao,
                            valorunitario: item.valorunitario,
                            quantidadedisponivel: item.quantidadedisponivel
                        });
                    });
                    return { results: results }
                }
            },
        }).on("change", change);    

    function change(el) {           
        var id = $(this).parent().prev('td').text();    
        var data = $(el.target).select2('data');            
        var cod_publicacao = data.cod_publicacao;
        var valorunitario = data.valorunitario;
        var quantidadedisponivel = data.quantidadedisponivel;
        var input = $(el.target).closest('tr').find('input[name="cod_publicacao'+id+'"]').last().val(cod_publicacao);
        var input2 = $(el.target).closest('tr').find('input[name="valorunitario'+id+'"]').last().val(valorunitario);
        var input3 = $(el.target).closest('tr').find('input[name="quantidadedisponivel'+id+'"]').last().val(quantidadedisponivel); 
    } 

    cnt++;

    function formatoptions(results) {   
        return results.text;
    }           

});

$("#remover_item").click(function(){
    if($('#tabela_publicacoes tr').size()>1){
        $('#tabela_publicacoes tr:last-child').remove();
    }else{
        alert('Erro, não foi possível remover');
    }
});
});
</script>
    
asked by anonymous 26.06.2014 / 20:08

1 answer

5

You need a function to call whenever a value is changed. Anything like:

function recalcular() {
    var somatorio = 0;
    var linhas = $('#tabela_publicacoes tr');
    linhas.each(function () {
        somatorio += $(this).find('input[name^="valorunitario"]').val() * $(this).find('input[name^="quantidadevendida"]').val();
    })
    $('#total').val(somatorio);
}

The idea is to have an event handler like this example:

$('#tabela_publicacoes').on('change', 'input', recalcular);

that triggers the function with each change. Within the example function I put, the idea is to go through each tr looking for the two fields. Since you do not know the number of them, you can ^= to tell jQuery that the name begins with this string.

And then just add these multiplications and put the value where it should be with $('#total').val(somatorio);

The reason I use delegation in .on() is that it stays connected to the table. If it were $('#tabela_publicacoes tr') then the new lines that were being created would not be checked.

    
26.06.2014 / 20:32