Poll: Was this article helpful for you?
You do not have permission to vote in this poll.
Yes
100.00%
1 100.00%
No
0%
0 0%
Total 1 vote(s) 100%
* You voted for this item. [Show Results]

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Filter tables with JQuery
#1
The HTML part between the <body></body> tags looks like this:

Code:
<h2>Filterable Table</h2>
<p>Type something in the input field to search the table for first names, last names or emails:</p>
<input id="myInput" type="text" placeholder="Search...">
<br><br>

<table>
  <thead>
    <tr>
      <th>First name</th>
      <th>Last name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody id="myTable">
    <tr>
      <td>John</td>
      <td>Doe</td>
      <td>john@example.com</td>
    </tr>
    <tr>
      <td>Mary</td>
      <td>Moe</td>
      <td>mary@example.com</td>
    </tr>
    <tr>
      <td>July</td>
      <td>Dooley</td>
      <td>july@example.com</td>
    </tr>
    <tr>
      <td>Anja</td>
      <td>Ravendale</td>
      <td>a_r@example.com</td>
    </tr>
  </tbody>
</table>

<p>Note that we start the search in tbody, to prevent filtering the table headers.</p>

The CSS part looks like this:

Code:
table
{
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th
{
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even)
{
  background-color: #dddddd;
}

The JQuery part looks like this:

Code:
$(document).ready(function()
                 {
  $("#myInput").on("keyup", function()
                  {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function()
                           {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

You can see the full source code on my CodePen
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  JavaScript - The filter() method Qomplainerz 0 398 04-04-2023, 07:41 AM
Last Post: Qomplainerz
Brick Get Started with JQuery Derp 0 3,037 09-10-2020, 01:37 PM
Last Post: Derp

Forum Jump:


Users browsing this thread: 6 Guest(s)