Try,
var xSum = 0;
$('#myTable tbody tr').each(function() {
xSum = 0;
$(this).find('td:contains(' + searchTerm + ')').each(function(){
xSum += parseInt($(this).next('td').text());
});
result.push(xSum);
});
Question
I am using the following lines to search through the rows of a table to check if any TDs contain my searchTerm which works fine so far.
My only problem is the case where searchTerm appears more than once in a row (like below). In this case it adds the values from a row as text instead of calculating the sum of them.
Example:
Here it currently returns 82,0,5
as searchTerm appears twice in the first row (once with the value 8 and once with 2).
Instead of this it should return 10,0,5
in this case.
Can anyone tell here me how I have to change my code to achieve this ?
My JS:
var searchTerm = "item1"
var result = new Array();
$('#myTable tbody tr').each(function() {
result.push(+($(this).find('td:contains(' + searchTerm + ')').next('td').text()));
});
alert(result);
My table:
<table id="myTable">
<thead>
<tr>
<th class="myHeader">Cat 1</th>
<th>Vol 1</th>
<th class="myHeader">Cat 2</th>
<th>Vol 2</th>
<th class="myHeader">Cat 3</th>
<th>Vol 3</th>
//...
</tr>
</thead>
<tbody>
<tr>
<td>item1</td><td>8</td><td>item2</td><td>7</td><td>item1</td><td>2</td>
</tr>
<tr>
<td>item3</td><td>5</td><td>item2</td><td>7</td><td>item2</td><td>4</td>
</tr>
<tr>
<td>item3</td><td>1</td><td>item1</td><td>5</td><td>item3</td><td>3</td>
</tr>
//...
</tbody>
</table>
Many thanks in advance, Tim.
La solution
Try,
var xSum = 0;
$('#myTable tbody tr').each(function() {
xSum = 0;
$(this).find('td:contains(' + searchTerm + ')').each(function(){
xSum += parseInt($(this).next('td').text());
});
result.push(xSum);
});