Sum of JS values

Asked

Viewed 34 times

0

Two things.

One must add up 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 Blur?

1 answer

2


Is returning Nan because if any of the fields is empty the parseFloat cannot convert null number, causing error in the sum of values, since Javascript will not be able to add a number with null.

You can put an operator || so that if one of the fields is empty, the field value assumes 0, avoiding the 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>
<input type="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">

  • It worked, but as I put more of a field calling the Blur?

  • In various ways... puts a class in the inputs and makes $(".nome_da_classe").blur(...

Browser other questions tagged

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