AAM
AAM

Reputation: 321

How to add search and filter to a column of a html table?

I want to add a search and filter feature to the State column of the table, preferably using jquery.

Here's the code for the table.

<div id="container">
    <div class="table-responsive"> 
<p>
Search: <input type="text" id="table-filter" value="">
</p>
        <table id ="table" class="table table-striped">

            <thead>
                <tr>
                    <th> First Name </th>
                    <th> Last Name </th>
                    <th> State </th>
                    <th> Date of Birth</th>
                    <th> Action </th>

                </tr>
            </thead> 
            <?php
            if (count($report) === 0) {
                echo "<tr>No Reports</tr>";
            } else {
                for ($i = 0; $i < count($report); $i++) {
                    echo
                    "<tr>
                        <td>{$report[$i]['First_Name']}</td>
                        <td>{$report[$i]['Last_Name']}</td>
                        <td>{$report[$i]['State']}</td>
                        <td>{$report[$i]['Date_of_Birth']}</td>
                        <td><a class=btn href='read.php?id=".$read['Id']."'>Read</a></td>

                    </tr>";

                }
            }
            ?>
</table>
</div>
</div>

main.js

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

});

I am very new to jquery. Any help would be appreciated.

Upvotes: 1

Views: 2289

Answers (2)

Mojtaba Zare
Mojtaba Zare

Reputation: 76

if you want to search in specific column try this: https://www.w3schools.com/howto/howto_js_filter_table.asp

for column 'state' you must change this line: td = tr[i].getElementsByTagName("td")[0]; to td = tr[i].getElementsByTagName("td")[2];

Upvotes: 1

Mojtaba Zare
Mojtaba Zare

Reputation: 76

try this tutorial and examples: jQuery Filters

if you don't understand it, tell me to help you!

Upvotes: 1

Related Questions