Issue
I have a very large table of data and I want to filter it by letter. I have buttons A-Z and 1 (for numeric) at the top of the page. When the user clicks a button, it should only show the rows that start with that letter (or a number if they click '1').
It works, but it is a bit slow to load since the table has thousands of rows. Is there a more efficient way of doing this that will help the page load faster?
// Limit to rows whose first cell's text starts with a given letter
$(".alphaList li button").click(function() {
var value = $(this).text().toUpperCase();
var cellText = '';
var firstChar = '';
if (isNumeric($(this).text())) {
// For 0-9
$("#alphaTable tr:not(#alphaTableHeader)").filter(function() {
cellText = $(this).find('td:first-child').text().toUpperCase().trim()
firstChar = cellText.substring(0, 1)
$(this).toggle(isNumeric(firstChar))
});
} else {
// For letters
$("#alphaTable tr:not(#alphaTableHeader)").filter(function() {
cellText = $(this).find('td:first-child').text().toUpperCase().trim()
firstChar = cellText.substring(0, 1)
$(this).toggle(firstChar == value)
});
}
});
<table id="alphaTable">
<thead>
<tr id="alphaTableHeader">
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>234</td>
<td>ABC</td>
<td>ABBC</td>
<td>BCD</td>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Solution
You could preemptively assign a special class and then reference it in your filter function...
// after the data is loaded...
$("#alphaTable tbody tr").each(function(i, o) {
let letter = $(o).find('td').eq(0).text().slice(0, 1)
$(this).addClass(`row_${letter.toUpperCase()}`);
})
// Limit to rows whose first cell's text starts with a given letter
$("#filters button").click(function() {
let letter = $(this).text().toUpperCase() ;
if (letter == 'RESET') return $("#alphaTable tbody tr").show();
$("#alphaTable tbody tr").hide();
$(`tr.row_${letter}`).show();
})
#alphaTable tbody tr,
tr[class^="row_"]{
display:none;
}
#alphaTable tbody tr.row_A{
display: table-row;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='filters'>
<button>1</button><button>A</button><button>Reset</button>
</div>
<table id="alphaTable">
<thead>
<tr id="alphaTableHeader">
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr><td>123</td><td>234</td><td>ABC</td><td>ABBC</td><td>BCD</td></tr>
<tr><td>A123</td><td>234</td><td>ABC</td><td>ABBC</td><td>BCD</td></tr>
</tbody>
</table>
Answered By - Kinglish
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.