Somar Campos Input

Asked

Viewed 602 times

0

I am trying to sum up some fields in a final input `.

I have a input id #TotalFR and would like that, according to the fields #CFR1, #CRF2, #CRF3, #CRF4 and #CRF5 are completed, the sum of the #TotalFR. I am using the script but I get the NAN value as a response.

 $('.vut').blur(function(){
   var id=$(this).attr("id").substr(3,1);
   $.ajax({
     url : 'custofr.php', 
     type : 'POST', /* Tipo da requisição */ 
     data: 'FR1=' + $('#FR'+id).val() + '&VUT1=' + $('#VUT'+id).val(), 
     dataType: 'json', 
     success: function(data){
       if(data.sucesso == 1){
         $('#CFR'+id).val(data.CFR1);
         var Valor1=parseFloat($('#CFR'+id).val());
         var Valor2=parseFloat($('#TotalFR').val());
         var TotFR = Valor1 + Valor2;
         $('#TotalFR').val(TotFR);
       }
     }
   }); 
   return false; 
 })
  • 1

    If you try to apply parseFloat to "" or a decimal with comma, you receive Nan as return. Nan + Num = Nan. I think #Totalfr is causing this problem by being empty. Try to exchange the parse float for the operator of +. I will not comment on this as a response because it is speculation, but if you solve it warns here :)

  • Willian, thank you very much for the clarification, it helped solve the problem. I made the insertion of a conditional that tests the field to see if it is empty, if yes, assigns the value 0, so the account proceeds correctly. I entered only the condition: if (isNaN(Valor2)){ Valor2 = 0; }

  • Thiago, @Williambarbosa’s suggestion was simpler, just use +$('#CFR'+id).val() (idem for the second value). +"" flipped 0. Then you don’t even have to check empty.

1 answer

1


If you try to apply parseFloat in an empty string ("") or in a decimal with comma, you get NaN as return and NaN + Num = NaN.

#TotalFR is causing this problem by being empty. Your best alternative is to use the operator +, that will try to convert its value to a number and return 0 when you find ""

+$('#CFR'+id).val()

Just remember that if you are using commas for the decimal numbers, Nan will still appear and you will need to make a comparison, checking if the value is Nan before using it. If you are not using dot, you can ignore this part.

Browser other questions tagged

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