Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

How to filter/search columns in HTML table?

$
0
0

I have followed this link on how to create/filter search a table. But I want to filter search for each column in my own table. Currently, it only searches for the First Name column. How can I do this?

This is the code:

myHTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">

<table id="myTable">
    <tr class="header">
        <th> First Name </th>
        <th> Last Name </th> 
        <th> Age </th>
        <th> Language </th>
    </tr>
    <tr>
        <td>John</td>
        <td>Kole</td>
        <td>18</td>
        <td>English</td>
    </tr>
    <tr>
        <td>Pearl</td>
        <td>Shine</td>
        <td>50</td>
        <td>Hindi</td>
    </tr>
   <tr>
        <td>Jacob</td>
        <td>Pool</td>
        <td>22</td>
        <td>Arabic</td>
   </tr>
   <tr>
        <td>David</td>
        <td>Struff</td>
        <td>30</td>
        <td>German</td>
   </tr>
</table>

<script>
    function myFunction() {
        var input, filter, table, tr, td, i, txtValue;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[0];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                    }
                else {
                    tr[i].style.display = "none";
                    }
                }       
            }
        }
</script>

How can I filter all columns for searching? Currently, it searches the First Name column only.


Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>