devasia2112
devasia2112

Reputation: 6044

jquery parseFloat, parseInt

I have the following situation, I'm using jquery and I need to sum up some fields on my form. I have found the NaN error in my subtotal field and total field. I have tried everything possible to avoid this type of error, I just need the SUM on this field. Everything in my form is working fine, only this 2 fields with a problem. I'm using parseFloat() and no response. Only a field with NaN

Follow my javascript code:

$(document).ready( function() {

        $('#valor, #taxa, #imposto, #envio, #taxa_adicional, #subtotal, #total').blur(function(){

                    // exemplo antigo var val = $('#valor').val();
                    var val = $('#valor').format({format:"#,###.00", locale:"br"});
                var tax = $('#taxa').format({format:"#,###.00", locale:"br"}); 
                var imp = $('#imposto').format({format:"#,###.00", locale:"br"}); 
                var env = $('#envio').format({format:"#,###.00", locale:"br"});
                var xat = $('#taxa_adicional').format({format:"#,###.00", locale:"br"}); 

                if(val == "") val = 0;
                if(tax == "") tax = 0;
                if(imp == "") imp = 0;
                if(env == "") env = 0;
                if(xat == "") xat = 0;

                    var subtotal = parseFloat("val") + parseFloat("tax") + parseFloat("imp") + parseFloat("env");
                var total = parseFloat(val) + parseFloat(tax) + parseFloat(imp) + parseFloat(env) + parseFloat(xat);

                    $('#subtotal').format({format:"#,###.00", locale:"br"});
                $('#total').val(total);
        })

});

Thanks in advance for any help on this matter! :-/

WARNING: I'm using a plugin called:
jquery.numberformatter - Formatting/Parsing Numbers in jQuery Written by Michael Abernethy

Upvotes: 6

Views: 51275

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 186103

HTML:

<div id="box">    
    <p> Valor: <input id="valor"> </p>
    <p> Taxa: <input id="taxa"> </p>
    <p> Imposto: <input id="imposto"> </p>
    <p> Envio: <input id="envio"> </p>
    <p> Taxa adicional: <input id="taxa_adicional"> </p>   
    <p> Subtotal: <span id="subtotal">0</span> </p>
    <p> Total: <span id="total">0</span> </p>   
</div>

JavaScript:

var options = {
        format: '#,###.00',
        locale: 'br'
    },
    inputs = $( 'input:text', '#box' ).get(),
    input_adicional = $( '#taxa_adicional' )[0],
    input_total = $( '#total' )[0],
    input_subtotal = $( '#subtotal' )[0];

and then:

$( inputs ).add( [ input_total, input_subtotal ] ).format( options );

$( inputs ).
    blur( function () {
        var total = 0,
            subtotal = 0;

        // on blur, format the field
        $( this ).format( options );

        // calculate the sum of all input fields
        $( inputs ).each( function () {
            total += +$( this ).parse( options );
        });

        // subtotal doesn't include the "additional" field  
        subtotal = total - $( input_adicional ).parse( options );

        // populate the SPAN's with the sums and format the nubmers
        $( input_subtotal ).text( subtotal ).format( options );
        $( input_total ).text( total ).format( options );
    }).
    focus( function () {
        // if the field contains the value 0, empty it
        if ( +$( this ).parse( options ) === 0 ) {
            this.value = '';
        }
    });

Live demo: http://jsfiddle.net/U9V6x/

Upvotes: 7

jcolebrand
jcolebrand

Reputation: 16035

It looks like you're using this plugin: http://code.google.com/p/jquery-numberformatter/

That plugin will take an element, parse the value according to the format, and reinsert it into the DOM, from what I can tell. So I'm going to assume that's the case.

$(document).ready( function() {
 $('#valor, #taxa, #imposto, #envio, #taxa_adicional, #subtotal, #total').blur(function(){
/*
  // first update all fields to have the correct format, so we can work with them later.
  $('#valor').format({format:"#,###.00", locale:"br"});
  $('#taxa').format({format:"#,###.00", locale:"br"}); 
  $('#imposto').format({format:"#,###.00", locale:"br"}); 
  $('#envio').format({format:"#,###.00", locale:"br"});
  $('#taxa_adicional').format({format:"#,###.00", locale:"br"}); 
*/
  //separating because I'm pretty sure this would work in place of all those lines of code:
  // needs testing though. If this doesn't work uncomment the previous block and delete this line
  $('#valor,#taxa,#imposto,#envio,#taxa_adicional').format({format:"#,###.00", locale:"br"}); 

  // then since the values have been formatted, let's extract just the floats like you wanted
  // going through the document.getElementById since the jQuery wrapper is useless overhead and you don't need a jQuery object back out.
  var val = parseFloat( document.getElementById('val').innerHTML );
  var tax = parseFloat( document.getElementById('taxa').innerHTML );
  var imp = parseFloat( document.getElementById('imposto').innerHTML );
  var env = parseFloat( document.getElementById('envio').innerHTML );
  var xat = parseFloat( document.getElementById('taxa_adicional').innerHTML );

  if( isNaN( val ) ) val = 0;
  if( isNaN( tax ) ) tax = 0;
  if( isNaN( imp ) ) imp = 0;
  if( isNaN( env ) ) env = 0;
  if( isNaN( xat ) ) xat = 0;

  var subtotal = val + tax + imp + env;
  var total = val + tax + imp + env + xat;

  $('#subtotal').val(subtotal).format({format:"#,###.00", locale:"br"});
  $('#total').val(total).format({format:"#,###.00", locale:"br"});
 });
});

Notice that I am only trying to help you have easier to read code. There are probably lots of ways to write this to get it leaner[1]


[1] less fat; less waste; ~ Perhaps this translates, perhaps it is an idiom?

Upvotes: 2

James Kovacs
James Kovacs

Reputation: 11661

When you're calculating your subtotal, you are calling parseFloat() on a series of strings, not the variables themselves. The line should be:

 var subtotal = parseFloat(val) + parseFloat(tax) + parseFloat(imp) + parseFloat(env);

Upvotes: 5

Metagrapher
Metagrapher

Reputation: 8932

This should work for you:

$(document).ready( function() {

    $('#valor, #taxa, #imposto, #envio, #taxa_adicional, #subtotal, #total').blur(function(){

                // exemplo antigo var val = $('#valor').val();
                var val = $('#valor').format({format:"#,###.00", locale:"br"});
            var tax = $('#taxa').format({format:"#,###.00", locale:"br"}); 
            var imp = $('#imposto').format({format:"#,###.00", locale:"br"}); 
            var env = $('#envio').format({format:"#,###.00", locale:"br"});
            var xat = $('#taxa_adicional').format({format:"#,###.00", locale:"br"}); 

            if(isNan(parseFloat(val))) val = 0;
            if(isNan(parseFloat(tax))) tax = 0;
            if(isNan(parseFloat(imp))) imp = 0;
            if(isNan(parseFloat(env))) env = 0;
            if(isNan(parseFloat(xat))) xat = 0;

                var subtotal = parseFloat("val") + parseFloat("tax") + parseFloat("imp") + parseFloat("env");
            var total = parseFloat(val) + parseFloat(tax) + parseFloat(imp) + parseFloat(env) + parseFloat(xat);

                $('#subtotal').format({format:"#,###.00", locale:"br"});
            $('#total').val(total);
    })

});

Upvotes: 1

Related Questions