Take the values of two inputs, perform the calculation and display in a third input

1

Well, I'm developing a form that will calculate the value of the freight and discount the debits to arrive at the net amount that the Driver has to receive. But I wanted some fields to display the values as the user completes the form.

For example the image, the "Weight Difference" field will calculate the "Output Weight" - "Weight of Arrival" to know the difference. Does anyone know of any JavaScript / jQuery tutorials that do something similar that I can build on?

 <script type="text/javascript">
            var tPesoSaida   = document.getElementById( 'ps' );
            var tPesoChegada = document.getElementById( 'pc' );
            var tPesoTotal   = document.getElementById( 'pt' );

            tPesoSaida.onkeyup=calcula;
            tPesoChegada.onkeyup=calcula;

            function calcula() {
                tPesoTotal.value = (tPesoSaida.value - tPesoChegada.value);
            }
        </script>
        <div class="small-2 large-4 columns">
            <label>Peso de Saída</label>
            <input type="text" value="0" placeholder="37000" name="PesoSaida" id="ps"/>
        </div>
        <div class="small-2 large-4 columns">
            <label>Peso de Chegada</label>
            <input type="text" value="0" placeholder="37090" name="PesoChegada" id="pc"/>
        </div>
        <div class="small-2 large-4 columns">
            <label>Diferença de Peso</label>
            <input type="text" value="0" name="PesoTotal"  id="pt" readonly="readonly" tabindex="-1"/>
        </div>
    
asked by anonymous 20.03.2016 / 21:18

1 answer

3

Here's a simple demonstration of how to do it in JS:

var tQtd = document.getElementById( 'qtd' );
var tVlr = document.getElementById( 'vlr' );
var tTot = document.getElementById( 'tot' );

tVlr.onkeyup=calcula;
tQtd.onkeyup=calcula;

function calcula() {
  tTot.value = tQtd.value * tVlr.value;
}
<input id="qtd" value="0" name="quantidade"><br>
<input id="vlr" value="0" name="valor"><br>
<input id="tot" value="0" name="total" readonly>

Note that there is no verification of the values, just put the basics to demonstrate how.

If you need more advanced things, such as controlling the decimal separator, and adjusting numeric formatting, we have answers explaining how to do it here:

  

How to calculate currency appearing decimal places in JS?

    
21.03.2016 / 02:02