Perform mathematical calculations with values from a dynamic table

Asked

Viewed 1,941 times

4

I have a form-Wizard table 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 customer.

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

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

Follow the image below the section quoted above:

tabela

Below I have inputs in which the discount is added and another that should show the total value of the sale based on the above information.

Follow picture:

tabela

My problem is I can’t do the calculation to know the total amount. This calculation shall be based on the unit value and quantity sold of each item.

If it was a static number of items I would know, but as each 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 disabled inputs:

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

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 fires the function with each change. Within the example function I have set, the idea is to go through each tr looking for the two fields. As you don’t know what number they are, you can go ^= to tell jQuery that the name starts with this string.

And then just add those 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 was $('#tabela_publicacoes tr') then the new lines that were being created would not be checked.

  • @Chico, I had forgotten the other function change you already have. So you can put this code inside it, or call this function recalcular from inside the other, at the end.

  • so I’m getting Nan as a return. Using . parseint() in $(this). find('input[name ="value value"]'). val() * $(this). find('input[name ="quantidadevendida"]'). val(); ?

  • @Chico, test this out: var vUnit = $(this).find('input[name^="valorunitario"]').val(); alert(typeof vUnit + ' - ' + vUnit); What gives you?

  • returns in Alert: Undefined - Undefined

  • @Chico, you’re putting that inside each()? Can do too console.log(linhas);, is closed?

  • first Alert gives Undefined - Undefined and then soon after another Alert appears written "string - 5.7(valuationary)" , put inside each

  • @Chico, okay, and where is it going NaN? can do the same with input quantidadevendida? Note that I invented this quantidadevendida I don’t know if he has that name... has?

  • The name is "quantityevendida" itself and the same thing happens to it, first Alert "Undefined-Undefined" and then "string - 2(which is the quantity entered in the input)" Nan appears in the $('#total value'field). val(somatorio);. In the input of the total value.

  • @Chico, you can click on the chat link above? ^

Show 5 more comments

Browser other questions tagged

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