how to perform calculations between 4 input, when loading page or change value

1

I have 4 input fields, being:

  • Cost that already comes with a value in value
  • The freight field, which when changed the value must be added to the cost and displayed in total
  • The discount field, which, when changing the value, must subtract from the total
  • I do not know how to do this.

    Follow the code with the input.

    Custo
    <input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,30'>
    
    <br>
    Frete
    <input type='text' class='form_campos calc' id='encargos' name='encargos'>
    
    <br>
    Desconto
    <input type='text' class='form_campos calc' id='desconto' name='desconto'>
    
    <br>
    Total
    <input type='text' class='form_campos calc2' id='total_val' name='total_val'>
        
    asked by anonymous 24.02.2016 / 14:28

    3 answers

    3

    Your HTML should be changed. Add the onkeyup property to the encargos and desconto fields.

    Custo
    <input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5.000,35' id="total_pedido">
    <br>
    Frete
    <input type='text' class='form_campos calc' id='encargos' name='encargos' onkeyup='calcular()'>
    <br>
    Desconto
    <input type='text' class='form_campos calc' id='desconto' name='desconto' onkeyup='calcular()'>
    <br>
    Total
    <input type='text' class='form_campos calc2' id='total_val' name='total_val'>
    

    Next you need to define the function calcular :

    //É necessário verificar se o campo "total_pedido" já foi renderizado e pode ser referenciado pelo script, 
    //por isso é preciso escutar o evento 'DOMContentLoaded'.
    var total = 0;
    document.addEventListener("DOMContentLoaded", function(event) { 
        total = document.getElementById("total_pedido").value;
        //Retiramos a formatação do campo e convertemos em uma string
        total = Number(total.replace(/[.]+/g,"").replace(",","."));
        //A função é executada para preencher o campo com o valor total
        calcular();
    });
    
    function calcular() {
        //Obtemos o valor do encargo e desconto
        var encargos = Number(document.getElementById("encargos").value);
        var desconto = Number(document.getElementById("desconto").value);
        var t = total + encargos - desconto;
        //Atualizamos o campo "total_val" com o valor total
        document.getElementById("total_val").value = t.toLocaleString('pt-BR');
    }
    

    See working here: link

        
    24.02.2016 / 15:04
    2

    Explaining the code below;

  • Through ID , we capture the input references of HTML ;
  • We have added an event for elements desconto and frete , so that they will execute the calcular() function whenever a key pressed is released;
  • We define the calcular function, which transforms the values of the inputs into numbers through the constructor Number and performs the calculation (total = custo + frete - desconto) ;
  • Finally, we assign to value of element total the calculation performed, formatting your presentation to 'pt-BR' with method toLocaleString
  • var frete = document.getElementById("encargos");
    var desconto = document.getElementById("desconto");
    var total = document.getElementById("total_val");
    var custo = document.getElementById("total_pedido");
    
    /*Criando eventos para executarem a função calcular sempre que uma tecla for pressionada*/
    desconto.addEventListener("keyup", function() {
      calcular();
    });
    
    frete.addEventListener("keyup", function() {
      calcular();
    });
    
    /*Função calcular; converte os valores dos inputs para float e então calcula (total = custo + frete - desconto)*/
    function calcular() {
      var valorTotal = Number(custo.value) + Number(frete.value) - Number(desconto.value);
      total.value = valorTotal.toLocaleString('pt-BR');
    }
    Custo
    <input type='text' class='form_campos calc' $input_total id='total_pedido' name='total_pedido' readonly='true' value='5000.30'>
    
    <br>Frete
    <input type='text' class='form_campos calc' id='encargos' name='encargos'>
    
    <br>Desconto
    <input type='text' class='form_campos calc' id='desconto' name='desconto'>
    
    <br>Total
    <input type='text' class='form_campos calc2' id='total_val' name='total_val'>

    References

    24.02.2016 / 14:58
    -1
        //obtenho o valor dos campos
        var vtotal = $('#total_pedido').val();
        var vfrete = $('#encargos').val();
        var desconto= $('#desconto').val();
    
        //efetuo o calculo que será exibido no ultimo input
        vtotal = ((vtotal+vfrete)-desconto);
        //escrevo o resultado no ultimo input
        $('#total_val').val(vtotal);
    
       // lembrando que as tags dessa pergunta mencionam javascript E JQuery
    
        
    24.02.2016 / 14:57