2011-08-31 46 views
1

我有一個表格,它有一個用於輸入數字值的文本框。該字段位於重複的行表中。字段ID是'金額'。我想在ID爲'amount'的文本字段中添加所有值,並將總和顯示在名爲'totals'的文本字段中,該字段位於單獨的表格中,但格式相同。我對jquery的使用經驗有限,實際上我設法創建並刪除了從堆棧溢出中讀取帖子的表格行。 我嘗試使用每個(),但它只適用於默認行的第一行。在jquery重複錶行中添加彙總

$("#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"><label for="amount"></label><input type="text"style="background-color:#CCC;"name="amount"id="amount"/></td><td>&nbsp;</td><td>&nbsp;</td></tr>'); 

}); 

的代碼添加值是這個(從網站得到它):

$("#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)); 
    } 

但是作爲說明,它僅適用於已加載的HTML第一默認行。在使用jquery添加行後輸入的值不會被總結。

回答

2

這是因爲你正在使用一個ID,你應該使用我認爲的類。

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

比賽只有第一個ID,而

$(".amount") 

會匹配所有的出現次數。嘗試改變你的HTML相應的一切都應該工作

+0

沒有工作。將所有內容都更改爲一個班級。問題在於,它並沒有將我輸入的值添加到我在飛行中創建的行中。我認爲總和函數應該迭代所有的HTML,並添加id \ class'amount'字段 – MaxI

+0

你可以在jsfiddle.net上發佈一個例子嗎? –