Amina Malik Amina Malik - 11 days ago 6
HTML Question

searching text within Html table

I just googling to find a script that I can use to find a text within HTML table.

Like I create a table of student names which have many columns and rows. I have a good script too that display whatever I try to search but it display full row...



function searchSname() {
var input, filter, found, table, tr, td, i, j;
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");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}

<input id='myInput' onkeyup='searchSname()' type='text'>

<table id='myTable'>
<tr>
<td>AB</td>
<td>BC</td>
</tr>
<tr>
<td>CD</td>
<td>DE</td>
</tr>
<tr>
<td>EF</td>
<td>GH</td>
</tr>
</table>





But know I am looking for making some changes to display exact text whatever I searched instead of full row like it will display text that I type to search and hide other unmatched fully....

Kindly let me know is it possible to display text only that I type to search within a table? Like if I try to find student name "AB" then it should display AB only instead of "AB BC".

Answer

This is much simpler than you are making it.

var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");

search.addEventListener("keyup", function(){

  for(var i = 0; i < cells.length; ++i){
    if(cells[i].textContent.toLowerCase() === search.value.toLowerCase()){
        cells.forEach(function(element){
            element.style.display = "none";
        });
        cells[i].style.background = "yellow";
        cells[i].style.display = "table-cell";
        break;
    } else {
        cells[i].style.background = "white";
        cells.forEach(function(element){
          if(cells[i] !== element){
            element.style.display = "table-cell";
          }
        }); 
    }    
  }

});
table, td { border:1px solid black; border-collapse: collapse;}
<input id='myInput'>

<table id='myTable'>
   <tr>
      <td>AB</td>
      <td>BC</td>
   </tr>
   <tr>
      <td>CD</td>
      <td>DE</td>
   </tr>
   <tr>
      <td>EF</td>
      <td>GH</td>
   </tr>
</table>