Reputation: 11377
I am using the following lines to search through the rows of a table to check if a TD contains my searchTerm which works fine so far.
Is there a way that instead of searching by row I can search by column here ? The reason why is that in my case a row can contain the same value multiple times but not a column which is what I need here.
My table has a standard structure with thead and tbody and I can add a colgroup or classes if needed.
My JS:
var searchTerm = "myText"
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>
</tr>
<tr>
<td>item3</td><td>5</td><td>item2</td><td>7</td>
</tr>
<tr>
<td>item2</td><td>1</td><td>item1</td><td>5</td><td>item3</td><td>3</td>
</tr>
//...
</tbody>
</table>
Many thanks in advance, Tim.
Upvotes: 1
Views: 634
Reputation: 2930
$('#myTable tbody tr:nth-child(myNumber)').each(function() {
var tdInMyNumberColumnValue = $(this).val();
//do stuff
}
use nth-child(myNumber)
(ex: nth-child(6)
) to check just the td in column you want. In example, column 6.
Of course, you can assign a class just the <td>
you want inspect and use an each related to this class selector.
Upvotes: 1
Reputation: 30993
You can loop on you columns and read each cell using nth:child
selector:
Selects all elements that are the nth-child of their parent.
Code:
var searchTerm = "myText"
var result = new Array();
for (var index = 0; index < $('#myTable thead th').length; index++) {
$('#myTable tbody td:nth-child(' + index + ')').each(function () {
if ($(this).is(':contains(' + searchTerm + ')'))
result.push(+($(this).next('td').text()));
});
}
alert(result);
Demo: http://jsfiddle.net/IrvinDominin/6Et6F/
Upvotes: 1