Add Fields Input

0

I'm trying to sum some fields into a 'final input.'

I have input id #TotalFR and I would like that, as fields #CFR1 , #CRF2 , #CRF3 , #CRF4 and #CRF5 are filled, the sum of this is displayed in #TotalFR . I'm using the script but I get the NAN value in 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; 
 })
    
asked by anonymous 02.10.2014 / 14:01

1 answer

1

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

#TotalFR is causing this problem because it is empty. Your best alternative is to use the + operator, which will try to convert its value to a number and return 0 when it finds ""

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

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

    
02.10.2014 / 14:33