Sums JS values

0

Two things.

A precise sum of the 3 values, but is returning NaN.

$('#valor').blur(function(){
   var valor = $("input[name=valor]").val();
   var descontos = $("input[name=descontos]").val();
   var juros = $("input[name=juros]").val();

   valor_cobrado = (parseFloat(valor) - parseFloat(descontos)) + parseFloat(juros);
   $("#valor_cobrado").val(parseFloat(valor_cobrado));

Not always discounts or interest are filled in the form.

And another question is, how do I declare more fields in the blur?

    
asked by anonymous 25.04.2018 / 21:43

1 answer

2

It is returning NaN because if any of the fields are empty the parseFloat can not convert null to number, causing error in the sum of the values since JavaScript will not be able to add a number with < in> null .

You can put a || operator so that if one of the fields is empty, the value of the field assumes 0 , avoiding NaN:

$('#valor').blur(function(){
   var valor = $("input[name=valor]").val() || 0;
   var descontos = $("input[name=descontos]").val() || 0;
   var juros = $("input[name=juros]").val() || 0;

   valor_cobrado = (parseFloat(valor) - parseFloat(descontos)) + parseFloat(juros);
   $("#valor_cobrado").val(parseFloat(valor_cobrado));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" name="descontos" placeholder="descontos">
<br>
<input type="text" name="juros" placeholder="juros">
<br>
<input type="text" id="valor" name="valor" placeholder="valor">
<br>
<input type="text" id="valor_cobrado" disabled placeholder="valor cobrado">
    
26.04.2018 / 00:11