Adding inputs with jquery and real-time

0

I need a jquery script to do the following:

TOTAL = Fine + Interest - Discount.

that computes even if one of the 3 inputs is not filled.

I found some examples on the internet, but everyone needs an action, a function or a button to press, but it has to be in real time. I tried this but I did not succeed ...

$(document).ready( function() {

    var multa = $('#multaSoValor').val();
    var juros = $('#jurosSovalor').val();
    var desconto = $('#descontoSoValor').val();

    var totalValorAdicionalDX = multa + juros - desconto;

    $('#totalValorAdicional').val('totalValorAdicionalDX'); 

});
    
asked by anonymous 09.06.2017 / 20:14

3 answers

-1

I made a simple and functional example, any questions just comment.

jQuery('input').on('keyup',function(){
  var m = parseInt(jQuery('#multa').val() != '' ? jQuery('#multa').val() : 0);
  
  var j = parseInt(jQuery('#juros').val() != '' ? jQuery('#juros').val() : 0);
  
  var d = parseInt(jQuery('#desconto').val() != '' ? jQuery('#desconto').val() : 0);
  
  jQuery('#total').val((m + j) - d);
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" placeholder="Multa" name="multa" id="multa" value="">
<input type="text" placeholder="Juros" name="juros" id="juros" value="">
<input type="text" placeholder="Desconto" name="desconto" id="desconto" value="">
<br>
<br>
<input type="text" name="total" id="total" value="">
    
09.06.2017 / 21:48
2

If with "real time" you mean when typed, here is an example with keyup which is the event triggered when the user releases a key on the keyboard:

$(document).ready(function() {
  $("#multaSoValor,#jurosSovalor,#descontoSoValor").on('keyup', function() {

    var multa = parseFloat($('#multaSoValor').val()) || 0;
    var juros = parseFloat($('#jurosSovalor').val()) || 0;
    var desconto = parseFloat($('#descontoSoValor').val()) || 0;

    var totalValorAdicionalDX = multa + juros - desconto;

    $('#totalValorAdicional').val(totalValorAdicionalDX);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="multaSoValor">
<input id="jurosSovalor">
<input id="descontoSoValor">

<input id="totalValorAdicional">
    
09.06.2017 / 20:21
1

Create a function that does this:

var fazerConta = (function(multa, juros, desconto, total) {
  return function() {
    total.value = (multa.value || 0) + (juros.value || 0) - (desconto.value || 0);
  }
})(
  document.getElementById('multaSoValor'),
  document.getElementById('jurosSovalor'),
  document.getElementById('descontoSoValor'),
  document.getElementById('totalValorAdicional')
);

And then put together a headset to detect changes and run the function in real time.

$('#multaSoValor, #jurosSovalor, #descontoSoValor').on('change', fazerConta);
    
09.06.2017 / 20:34