JSFiddle - React, Tailwind, and code Playground

by Alphonsio

HTML

<h2>Tableau avec Filtrage des Colonnes</h2>

<input type="text" id="filterInput" placeholder="Filtrer par prénom..." onkeyup="filterTable()">

<table id="myTable">
    <thead>
        <tr>
            <th>Nom</th>
            <th>Prénom</th>
            <th>Âge</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Dupont</td>
            <td>Jean</td>
            <td>25</td>
        </tr>
        <tr>
            <td>Durand</td>
            <td>Marie</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Martin</td>
            <td>Pierre</td>
            <td>45</td>
        </tr>
    </tbody>
</table>

CSS

body {
  background-color: #f8f8f8;
}

table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  background-color: #eee;
}
th {
  background-color: #ddd;
}

JavaScript

function filterTable() {
    const input = document.getElementById('filterInput');
    const filter = input.value.toUpperCase();
    const table = document.getElementById('myTable');
    const tr = table.getElementsByTagName('tr');

    for (let i = 1; i < tr.length; i++) {
        const td = tr[i].getElementsByTagName('td')[1]; // Colonne Prénom
        if (td) {
            const txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = '';
            } else {
                tr[i].style.display = 'none';
            }
        }
    }
}