logiko
logiko

Reputation: 130

Sum of the value of dynamic elements

I am trying to get real time summation of the value of dynamic elements, but I can't get it. You can see my DEMO here.

My code is given below.

My Javascript is:

<script>
    $(document).ready(function(){
        $(".input_ttotal").each(function() {

            $(this).keyup(function(){
                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;

        $(".input_ttotal").each(function() {       
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
            }

        });
        $("#sum").html(sum.toFixed(2));
    }
</script>

Finally, my HTML is:

<form action="" method="POST">

<div class="yes">
    <div id="cost1" class="clonedCost" style="display: inline;">
        <table  border="0">
          <tr>          
            <td><label class="total" for="total">Total 1</label></td>
          </tr>
          <tr>
            <input class="input_ttotal" id="ttotal" type="text" name="ttotal[]" /></td>
          </tr>
        </table>
    </div>
    <div id="addDelButtons_cost"><input type="button" id="btnAdd" value=""> <input type="button" id="btnDel" value=""></div>

     <p>Sum is:<span id="sum">0</span></p>
</div>

</form>

Upvotes: 0

Views: 1099

Answers (2)

vee
vee

Reputation: 38645

The problem seems to be with newly added elements. You could use the jQuery on method to bind keyup event on those elements. Also you don't need to loop through the elements and bind the keyup event on each an every one of them like you've done. You could do it with one statement without the loop like follows:

$(document).on('keyup', '.input_ttotal', function() {
    calculateSum();
});

Or alternatively on one like as CORRUPT mentioned in the comment below:

$(document).on('keyup', '.input_ttotal', calculateSum);

Upvotes: 2

Samuel Liew
Samuel Liew

Reputation: 79022

The keyup is only working for the first element. The new inputs are not having the handler bound to them. Instead of using .each() to bind the elements once on page load, use .on() to handle those that are also dynamically attached.

Change

$(".input_ttotal").each(function() {
    $(this).keyup(function() {
        calculateSum();
    });
});

To

$("form").on('keyup', '.input_ttotal', function() {
    calculateSum();
});

Click to see it in action: http://jsfiddle.net/ByLrz/1/

Upvotes: 1

Related Questions