Reputation: 3
There is a very pithy method for bootstrap table filtering on W3Schools: https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_filters_table&stacked=h
Here is the jQuery/Javascript portion (uses a text box to filter the table):
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
However, the example table provided has three columns (first name, last name, e-mail), and this will search all three. I would like a very simple way to refine this to search only a particular column (e.g. e-mail only) or only two of the columns (e.g. first name and last name only). I can see some much lengthier ideas in other answers, but since this looks so straightforward, I though I might ask.
Upvotes: 0
Views: 3997
Reputation: 751
Change your filter function to this:
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).find('td:eq(0), td:eq(1)').text().replace(/\s+/g, ' ').toLowerCase().indexOf(value) > -1)
});
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<input class="form-control" id="myInput" type="text" placeholder="Search..">
<br>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>[email protected]</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
With find('td:eq(0), td:eq(1)')
you can search by first and second columns. Change the condition to whatever it suites you. If you want to search only by email (3rd column), the condition will be find('td:eq(2)')
Upvotes: 1
Reputation: 2104
You can simply select td
for which you want to search. You can use below code if you want to search in first or last td
as below:
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).find("td:first").text().toLowerCase().indexOf(value) > -1)
});
});
});
You can use :last
to select last element if needed. If you want to select second element then you can use eq
selectore as well as find("td:eq(1)")
.
If you want to apply search for two columns, you can simply copy the search selector in find as find("td:eq(0),td:eq(2)")
which will search in First and Last column.
Thanks and hopefully it helps you.
Upvotes: 1