Code a simple html page with filter applied on table

 


<!DOCTYPE html>

<html>

<head>

    <title>Table Filter Example</title>

    <style>

        table {

            border-collapse: collapse;

            width: 100%;

        }


        th, td {

            border: 1px solid black;

            padding: 8px;

            text-align: left;

        }

    </style>

</head>

<body>

    <input type="text" id="filterInput" placeholder="Filter">

    <br><br>

    <table id="myTable">

        <tr>

            <th>Name</th>

            <th>Age</th>

            <th>City</th>

        </tr>

        <tr>

            <td>John Doe</td>

            <td>25</td>

            <td>New York</td>

        </tr>

        <tr>

            <td>Jane Smith</td>

            <td>30</td>

            <td>London</td>

        </tr>

        <tr>

            <td>Mark Johnson</td>

            <td>35</td>

            <td>Paris</td>

        </tr>

        <tr>

            <td>Sarah Williams</td>

            <td>28</td>

            <td>New York</td>

        </tr>

    </table>


    <script>

        const filterInput = document.getElementById("filterInput");

        filterInput.addEventListener("keyup", filterTable);


        function filterTable() {

            const filterValue = filterInput.value.toLowerCase();

            const table = document.getElementById("myTable");

            const rows = table.getElementsByTagName("tr");


            for (let i = 1; i < rows.length; i++) {

                const row = rows[i];

                const cells = row.getElementsByTagName("td");

                let found = false;


                for (let j = 0; j < cells.length; j++) {

                    const cell = cells[j];


                    if (cell) {

                        const cellValue = cell.textContent || cell.innerText;


                        if (cellValue.toLowerCase().indexOf(filterValue) > -1) {

                            found = true;

                            break;

                        }

                    }

                }


                if (found) {

                    row.style.display = "";

                } else {

                    row.style.display = "none";

                }

            }

        }

    </script>

</body>

</html>


Comments

Popular posts from this blog

Java Practice Questions MCQ

HackerRank Introduction Challenges - Java

SQL