Jump to content

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


MockY
Go to solution Solved by codefossa,

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/

Edited by MockY
Link to comment
Share on other sites

  • Solution

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));
    }
});
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.