I have a situation where I need to calculate sum taking the values from TD id="amount" which will be repeated/duplicated several times. Ajax only takes value from 1st TD and rest is ignored.
// ajax part
function CalculateMonthlySalary() {
var tot = 0;
$("#amount").each(function() {
tot += parseInt($(this).text());
$("#divEstimatedMonthlySalary").html(addCommas(tot.toFixed(0)))
});
}
<tr data-row-id="1" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Basic Salary">Basic Salary</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="2000.00">2000.00</td>
</tr>
<tr data-row-id="2" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Housing Allowance">Housing Allowance</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="2000.00">2000.00</td>
</tr>
<tr data-row-id="3" class="sum">
<td class="editable-col" contenteditable="true" col-index='1' oldVal="Transport Allowance">Transport Allowance</td>
<td id="amount" onkeyup="CalculateMonthlySalary();" class="editable-col" contenteditable="true" col-index='2' oldVal="1000.00">1000.00</td>
</tr>
<div class="Heading2">Total Monthly Salary</div>
<div style="clear:both;"></div>
<br>
<div style="margin-left:20px;" id="divEstimatedMonthlySalary" class="Web1">0</div>
Any idea where I am doing wrong ?
Just add custom attribute amount into your td tag.
<!-- Like this -->
<td amount ....>xxx</td>
//change the selector in function with custom attribute amount
function CalculateMonthlySalary(){
var tot=0;
//"#amount" to "td[amount]"
$("td[amount]").each(function() {
tot += parseInt($(this).text());
$("#divEstimatedMonthlySalary").html(addCommas(tot.toFixed(0)))
});
}
It's doing this because you are using ID's and not classes. ID's are only to be used for one element. Change it to a class then loop through each to get it work.
id should be unique in a web document. Javascript also assumes this, and thus ignores every element after it has found an element matching to the id.
you should use class name for selecting the td instead.