I copied and pasted this jQuery code in my project from the w3schools website. It filters rows of my table. It works
$(document).ready(function () {
$("#my-search-input").on("keyup", function () {
let value = $(this).val().toLowerCase();
$("#table-body tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
<!-- example table -->
<table class="table">
<input class="form-control" id="my-search-input" type="text" placeholder="Search...">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Last name</th>
<th scope="col">Department</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
<td>John</td>
<td>Doe</td>
<td>IT</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
<td>HR</td>
</tr>
</tbody>
</table>
But I don’t like using code I don’t understand. I hoped completing the free jQuery courses here on Codecademy would help, but it didn’t. The lessons were great, but they covered only a small portion of jQuery, not every element the script above has. I stop understanding at filter()
. I tried reading the docs. What I don’t understand is this
-
filter()
doesn’t hide anything, does it? It simply returns a subset that specifies certain criteria. Why does it hide/show rows? -
filter()
can accept a function, but, as I understand it, it should be a boolean function. Istoggle()
a boolean function? What booleans does it return? -
toggle()
does hide/show elements. So, perhaps, it’stoggle()
that does all the work, notfilter()
, isn’t it? What do I needfilter()
for then?
I tried writing my own code that I do understand. But it doesn’t work. For example
$(document).ready(function () {
$("#my-search-input").on("keyup", function () {
let value = $(this).val().toLowerCase();
let rows = $(this).find('tbody').children();
rows.toggle(rows.text().toLowerCase().indexOf(value) > -1);
});
});
So it’s supposed to toggle()
the rows according to the boolean expression. But nothing happens
To recap:
- please help me understand the w3 code by answering my questions
- please tell me why my solution doesn’t work as expected (additionally, maybe you can tweak it a little so it works?)