开发者

Adding Totals in Jquery repeat table row

I have a table that has a textfield for inputing numeric values. This field is in a repeated row table. The field id is 'amount'. I want to add all values in the text fields with ID 'amount' and display the sum in a textfield called 'totals' which is in a seperate table but in the same form. I have limited experience with jquery and I actually managed to create and delete a table row from reading posts on stack overflow. I tried using each() but it only works with the first row which is the default row.

$("#addrow").click(function(){
        alert("It works.");


        //$('#description tr:last').after('<tr>...</tr>');
         $('#description tr:last').after('<tr><td align="center"><label for="description"></label><input name="description"type="text"style="background-color:#CCC;" id="description" size="70"/></td><td align="center开发者_JS百科"><label for="amount"></label><input type="text"style="background-color:#CCC;"name="amount"id="amount"/></td><td>&nbsp;</td><td>&nbsp;</td></tr>');

});

The code for adding values is this one(got it from a site):

 $("#amount").each(function() {

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

    var sum = 0;
    //iterate through each textboxes and add the values
    $("#amount").each(function() {

        //add only if the value is number
        if(!isNaN(this.value) && this.value.length!=0) {
            sum += parseFloat(this.value);
        }

    });
    //.toFixed() method will roundoff the final sum to 2 decimal places
    $("#sum").html(sum.toFixed(2)); 
    }

However as stated, It only works with the first default row that was loaded with the html. Values I input after adding a row using jquery doesn't get summed up.


This is because you are using an id where you should be using a class i think.

$("#amount") //using each here makes no sense as you have only one element returned

matches only the first id while

$(".amount")

would match all the occurences. Try to change your html accordingly and everything should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜