Cet article présente comment implémenter une fonctionnalité de recherche de données dans un tableau.

Code HTML :

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Rechercher..."> <table id="myTable"> <tr class="header"> <th style="width:60%;">Nom</th> <th style="width:40%;">Ville</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Allemagne</td> </tr> <tr> <td>Berglunds snabbkop</td> <td>Suède</td> </tr> <tr> <td>Island Trading</td> <td>Royaume-Uni</td> </tr> <tr> <td>Koniglich Essen</td> <td>Allemagne</td> </tr> </table>

Code CSS :

#myInput { background-image: url('https://static.jyshare.com/images/mix/searchicon.png'); /*Bouton de recherche*/ background-position: 10px 12px; /*Positionner le bouton de recherche*/ background-repeat: no-repeat; /*Image sans répétition*/ width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myTable { border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 18px; } #myTable th, #myTable td { text-align: left; padding: 12px; } #myTable tr { /*Ajouter une bordure au tableau*/ border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { /*Ajouter un arrière-plan à l'en-tête du tableau et aux lignes au survol de la souris*/ background-color: #f1f1f1; }

Code JavaScript :

function myFunction() { //Déclarer les variables var input, filter, table, tr, td, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); //Parcourez chaque ligne du tableau et trouvez les correspondances for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } }

Astuce :Si vous avez besoin d'une correspondance sensible à la casse, vous pouvez supprimer la méthode toUpperCase().

Astuce :Si vous devez rechercher la deuxième colonne (Ville), vous pouvez changer tr[i].getElementsByTagName('td')[0]en[1]La valeur d'index commence à 0 ; c'est-à-dire, 0 est la première colonne, 1 est la deuxième colonne, et ainsi de suite.

Démo en ligne