Desired Behaviour
Show or hide tables (whole tables, not table cells) based on search matches in the first two columns of all tables - if there is a match in the first or second <td>
of a <tr>
, show the table, else hide the table.
What I've Tried
$("input").on("keyup", function() {
var matcher = new RegExp($(this).val(), "gi");
$(".my_table")
.hide()
.filter(function() {
return matcher.test($(this).find("td").text());
})
.show();
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 50%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<table class="my_table">
<thead>
<tr>
<th>
First Name
</th>
<th>Last Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<tr>
<td>David</td>
<td>Johnman</td>
<td>Here is some text</td>
</tr>
<tr>
<td>Felix</td>
<td>Mann</td>
<td>Cake</td>
</tr>
<tr>
<td>Peter</td>
<td>Pan</td>
<td>Green green grass of home</td>
</tr>
</table>
<br><br>
<table class="my_table">
<thead>
<tr>
<th>
First Name
</th>
<th>Last Name</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<tr>
<td>David</td>
<td>Stone</td>
<td>Here is text</td>
</tr>
<tr>
<td>Trevor</td>
<td>Barry</td>
<td>Cake</td>
</tr>
<tr>
<td>Xylophone</td>
<td>Greet</td>
<td>Green green grass of home</td>
</tr>
</table>
Not averse to putting classes on the first two table cells in each row if that helps target the search, just not entirely sure how to target the instance of the table that is being filtered.
Eventually I am wanting to start the filtering after typing 3 characters, so will probably wrap the code in a conditional check on input length, and show all tables when input length is 0 (after backspacing content).
You can limit the search to the :first-child
and second child (:nth-child(2)
) or-ed together:
return matcher.test($(this).find("td:first-child,td:nth-child(2)").text());
Alternatively, as you have suggested, you can add a class to the first two td
, e.g. searchable
, and refine the query string to td.searchable
.