Reputation: 349
How can I count how many table rows are shown after filtering?
I've tried running this script, but it shows total rows, not currently shown rows:
function CountRows() {
var rowCount = 0;
var table = document.getElementById("filter_table");
var rows = table.getElementsByTagName("tr")
for (var i = 0; i < rows.length; i++) {
if (rows[i].getElementsByTagName("td").length > 0) {
rowCount++;
}
}
var message = "Showing: " + rowCount;
alert(message);
}
Location: http://kissbandstree.com/count_rows.js
There is no error message.
This is the filter script: http://kissbandstree.com/multifilter.js
This is the test page: http://kissbandstree.com/artists2.php
I want to show how many rows are showing after a filter has been applied.
This is the relevant PHP / HTML part:
<?php
// Fetch all filenames in the kiss_artists directory
$artists = glob('kiss_artists/*.txt');
?>
<table class="standard">
<tr>
<td>
<?php echo"Items in table: " . count($artists) . ". Showing: XXX. Table is sortable. Artists names are links to simple individual pages. Date is when the entry was modified."; ?>
<input id="clickMe" type="button" value="clickme" onclick="CountRows();">
</td>
</tr>
</table>
Upvotes: 0
Views: 3166
Reputation: 147146
You should be able to skip the hidden rows by adding a check for visibility to your loop:
for (var i = 0; i < rows.length; i++) {
if (rows[i].style.display == 'none') continue;
if (rows[i].getElementsByTagName("td").length > 0) {
rowCount++;
}
}
// for the header row
rowCount--;
Since there is a header row you need to subtract one from your count.
Upvotes: 1
Reputation: 1220
You can check all the count of visible rows only.. because by seeing that page, you are hiding rows that are not relevant to the filter.
I have to minus one count from total just because of header row was calculated too.
Also, Since you use jQuery in that page, this should be the simplest solution
function countRows(){
let rowCount = $('#filter_table tr:visible').length - 1;
var message = "Showing: " + rowCount;
alert(message);
}
Upvotes: 2