SBB
SBB

Reputation: 8970

javascript math with dynamic fields

I have a form with school classes on it. There could be any number of classes on this form, each with 2 fields. Cost of books and cost of tuition.

I have a 3rd field called grand total which I want to update as they are typing in the costs in the other fields.

This is how I have it set up:

    $(document).on( "keyup", ".cost", function(){
        theCost = parseFloat($(this).val(), 2) || 0;
        grandTotal(theCost);
    });


    // Calculate the total
    function grandTotal(theCost){
        totalCost = (totalCost + theCost);
        console.log(totalCost);
    }

Since this runs on every keyup, if i type in 44 it just adds 4+4.

Is there a better way to do this in order to get the value of the field and not each number typed?

Upvotes: 0

Views: 85

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23132

Many times, I see this situation handled with an Update Total button, so the action is deliberate.

$('#updateTotalButton').click(function(){
    $('.cost').each(function() {
        theCost = parseFloat($(this).val(), 2) || 0;
        grandTotal(theCost);
    });
});

// Calculate the total
function grandTotal(theCost){
    totalCost = (totalCost + theCost);
    console.log(totalCost);
}

Upvotes: 0

Shomz
Shomz

Reputation: 37701

The easiest way would probably be to make theCost an array of costs for each class and then simply sum the array to get the grandTotal (a simple grandTotal = theCost.reduce(function(a, b) { return a + b; }); would work). That way it would still work with your keyup event because it would take the full numbers every time it does the calculation (so it would always take 44 instead of 4 + 4, etc).

Upvotes: 0

BReal14
BReal14

Reputation: 1584

I would suggest iterating through the whole document of fields and re-calculating everything every time instead of trying to add a field at a time to the total cost. Any in-between method like this will result in an inaccurate total in many cases like you found, and additional quick-typing events, or edits.

Upvotes: 0

Joe
Joe

Reputation: 15802

It depends on your interface and how you want it to work.

.blur will fire when an input loses focus. You could listen for keyup or keydown and match the [Enter] key if you want to do it like that, or you could bind it to a specific button. There isn't one catch-all answer.

One other thing worth noting - you shouldn't bind events to the document in most cases. Find a sensible parent element that's not too far away from your input for it to bubble, then bind to that. A slightly better example would be $('form').on('keyup', '.cost'... so the event can be constrained to just <form>s which are relatively sparse in most pages.

Upvotes: 1

Related Questions