Realtime Search in HTML Table with JS
117   1  

Realtime Search in HTML Table with JS

  18 Nov 2017
  Coding Category
Realtime Search in HTML Table with JS

We want to filter simple HTML Table, when user typing query in a Text Input. We use simple code to create Text Input and Table and then, listen to Input Event to call our Filtering Function. You can use these in Pure JavaScript or jQuery as you want.


1. To create Text Input and Table use this code (or something like this, I use onkeyup for keyboard input event listener and also use PHP to create my table):


<input type="text" id="fl-search" onkeyup="searchfl()">

<table id="fl-table">

    <thead>

        <tr>

            <th>Title1</th>

            <th>Title2</th>

            <th>Title3</th>

        </tr>

    </thead>

    <tbody>

        <?php

            $query = "SELECT * FROM mytable ORDER BY id DESC";

            if ($result = mysqli_query($db,$query)) {

                while ($row = mysqli_fetch_array($result)) {

        ?>

        <tr>

            <td><?php echo $row['subtitle1']; ?></td>

            <td><?php echo $row['subtitle2']; ?></td>

            <td><?php echo $row['subtitle3']; ?></td>

        </tr>

        <?php

                }

            }

        ?>

    </tbody>

</table>


2. And finally add our Function to linked js file:


function searchfl() {

    var input, filter, table, tr, td, i;

    input = document.getElementById('fl-search');

    filter = input.value.toUpperCase();

    table = document.getElementById('fl-table');

    tr = table.getElementsByTagName('tr');

    for (i = 0; i < tr.length; i++) {

        td = tr[i].getElementsByTagName('td')[0]; //search on first column, if you want to filter others, use index > 0

        if (td) {

            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {

                tr[i].style.display = '';

            } else {

                tr[i].style.display = 'none';

            }

        }

    }

}

Author: Ismael Azaran

Do you like it? Share it with your friends.

Categories

Tags