Jump to content

Show running total from text boxes (dynamic amount of boxes)


MockY

Recommended Posts

I'm looking for a solution that adds up a running total from a non predefined amount of text boxes.

If the form that I use already have 2 text boxes when the page loads, it works just fine for those boxes.

 

However, my issue appears when I create new text boxes on the fly.

 

Take a look at this Fiddle to get the full picture of what's going on. (In case you use Opera, the sum does not work)

 

http://jsfiddle.net/JtXVR/

You could try something like this.  Using $.on() instead.

Link: http://jsfiddle.net/JtXVR/7/

 

 

$(document).ready(function()
{
    $("body").on("keyup", ".txt", calculateSum);
    
    function calculateSum()
    {
        var sum = 0;
        
        $(".txt").each(function()
        {
            if (!isNaN($(this).val()) && $(this).val().length != 0)
                sum += parseFloat($(this).val());
        });
        
        $("#sum").html(sum.toFixed(2));
    }
});

Elegant! Thanks.

 

I will be using your solution.

 

Since the last row is duplicated, if there are any values in the box, this will be duplicated as well. It would be nice if by default the box was empty. But that has little to do with the original question, so this thread is solved.

 

Thanks again.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.