I am trying to search html table using jquery, and from examples seen in internet i managed to get it to work, but i would like to do more advanced search.
I want search to include also next row from matched row (regardless if there is any match there), how could i achieve this ?
I have this HTML at moment:
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("tbody tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<p>
<input id="myInput" type="text" placeholder="Search..">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</p>
<table>
<thead>
<tr>
<th style='text-align:left;'>Item</th>
</tr>
</thead>
<tbody>
<tr>
<td>Porsche</td>
</tr>
<tr>
<td>Joe</td>
</tr>
<tr>
<td>Ferrari</td>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Lada</td>
</tr>
<tr>
<td>Vladimir</td>
</tr>
</tbody>
</table>
</body>
</html>
So goal would be to always include +1 row to matched row ,for example if i would search Ferrari, i would like it to show Ferrari row and John row.
$("#myInput").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("tbody tr").filter(function () {
if ($(this).text().toLowerCase().indexOf(value) > -1) {
$(this).addClass("filteredNode");
}
else {
$(this).removeClass("filteredNode");
}
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
.filteredNode + tr {
display: table-row !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
</style>
</head>
<body>
<p>
<input id="myInput" type="text" placeholder="Search..">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</p>
<table>
<thead>
<tr>
<th style='text-align:left;'>Item</th>
</tr>
</thead>
<tbody>
<tr>
<td>Porsche</td>
</tr>
<tr>
<td>Joe</td>
</tr>
<tr>
<td>Ferrari</td>
</tr>
<tr>
<td>John</td>
</tr>
<tr>
<td>Lada</td>
</tr>
<tr>
<td>Vladimir</td>
</tr>
</tbody>
</table>
</body>
</html>