SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Mar 2011
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Show running total from dynamic amount of text boxes

    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/

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Elements that are added on the fly do not have the event handlers attached to them.
    In this case you will need to use event delegation, something like:

    Code:
    $("table").on("keyup", ".txt", function () {
        calculateSum();
    });
    which assumes jQuery 1.9.1 or higher.

    If you are stuck with an older version, you'll need to look at live() instead.

  3. #3
    SitePoint Member
    Join Date
    Mar 2011
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That worked beautifully. Thank you.

    On a side note, since the last row in a table in duplicated, if there are value in the text boxes, these will be duplicated as well. Do you see any obvious way to force the fields to be empty for the duplicated row(s)? I can't take credit for the javascript I've gathered for this project, so I've only made some minor changes here and there.

    Since the latter question has little to do with the topic, this thread is solved.

    Thanks again.

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,939
    Mentioned
    215 Post(s)
    Tagged
    12 Thread(s)
    Quote Originally Posted by MockY View Post
    On a side note, since the last row in a table in duplicated, if there are value in the text boxes, these will be duplicated as well. Do you see any obvious way to force the fields to be empty for the duplicated row(s)?
    Sure. Just do this before appending the row:

    Code:
    $(newRow).find("input").val("");
    Her's an updated fiddle.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •