Reputation: 1296
I have a table with various columns and many rows. To simplify this, I just need to know how many rows are billable (in this case, column 2). In other words, how many rows in column 2 have the text "y"? Anyways, this is what I've tried so far:
jQuery
var billable = 0;
// attempt 1
table.rows().eq(1)( function () {
if(table.data() === 'y'){
//priceTotal+=parseInt(table.cell(row,0).data());
alert('This is the billable column, now count which equal "y".')
billable++;
}
});
// attempt 2
column(2).data() === "y"){
alert('This is the billable column, now count which equal "y".')
billable++;
}
Upvotes: 2
Views: 5711
Reputation: 85518
Use the dataTables API to cycle through all the rows :
var rowCount = table.rows()[0].length;
for (var row=0;row<rowCount;row++) {
if (table.cells(row, 1).data().indexOf('y')>-1) {
billable++;
}
}
alert(billable+' total');
forked fiddle -> http://jsfiddle.net/3C9Rk/
Note : Cells
is zerobased, and the number of rows can be found multiple ways, the above is just an API example.
Upvotes: 1
Reputation: 1101
with jquery we can select element by the index in the parent Element: :nth-child()
, so simply:
$( ".our-table td:nth-child(2):contains('y')" ).length;
Just added to HTML (just in case):
<tbody class="our-table">
and using the :contains()
Selector, we selecting all the <td>
in column 2, that :contains('y')
demo: http://jsfiddle.net/s827x/6/
Upvotes: 2
Reputation: 2936
isherwood's example would work for an exact match, but this would also work if you're only looking for matches that contain a search term:
function countContaining(table, search) {
var count = 0;
$(table).find('td').each(function(e) {
if (e.innerHTML.indexOf(search) > 0) {
count++;
}
});
return count;
}
Upvotes: 0