i_me_mine
i_me_mine

Reputation: 1433

sum of numbers not having desired effect jquery

I'm relatively new to javascript/jQuery and I'm having trouble getting my expected outcome. I would like the total to be shown even if only one input has a value, otherwise I want 0 to be shown. However right now it requires all 3 values to be input before it will show the sum. It will not simply add the next input onto the total as I type into an input. I can imagine a series of lengthy conditional statements that would cross check each input for .length and return the total based on each input. Surely there has to be an easier/cleaner way. If this were java I would use total += (variable) and it would total them as I went. That doesn't seem to work here.

    $('#invoice_labor, #invoice_materials, #invoice_other').keyup(function() {  
        if ($('#invoice_labor').length || $('#invoice_materials').length || $('#invoice_other').length ) {
            updateTotal();        
        } else {
            $('#invoice_total').html(0);
        }
    });     
    var updateTotal = function () {
        var input1 = parseFloat($('#invoice_labor').val(), 2);
        var input2 = parseFloat($('#invoice_materials').val(), 2);
        var input3 = parseFloat($('#invoice_other').val(), 2);
        var total = input1 + input2 + input3;      
        $('#invoice_total').html(total);
        $("#invoice_total").html(parseFloat($("#invoice_total").html()).toFixed(2));         
    };  

and here is the fiddle I was tinkering with.

So I want the total to change regardless of which field I type a number into. If it's only one, total that add that to the total variable and return it. If it's any combination of two then combine them and add them to the total. Thanks for the help.

Upvotes: 1

Views: 67

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('#invoice_labor, #invoice_materials, #invoice_other').keyup(function() {  
    updateTotal();        
});     
var updateTotal = function () {
    var input1 = parseFloat($('#invoice_labor').val()) || 0;
    var input2 = parseFloat($('#invoice_materials').val()) || 0;
    var input3 = parseFloat($('#invoice_other').val()) || 0;
    var total =  input1 + input2 + input3;      
    $("#invoice_total").html(total.toFixed(2));         
};  

Demo: Fiddle

Your fiddle has few problesm

  1. You were registering the input keyup event, in the body keyup handler which was wrong - it will cause the first keystroke not to be recognised and will fire multiple updatetotal calls in subsequent calls
  2. If a field is empty parseFloat will return NaN which when added will result in NaN as the result
  3. parseFloat takes only one argument

Upvotes: 2

Related Questions