TheRogerLAB Codes

Filter and hightlight search results in a table

  July, 2021

Introduction

Sometimes it is not enough to filter the search results, we also need to hightlight the matches found. Here is an option

Step 1: Define some HTML

<input type='text' placeholder='Filter here...' onkeyup='filterAndHightlight()'>
<span class='clearFilter' onclick='clearFilter()'>×</span>
<table>
 <thead>
  <tr>
   <th>EMAIL</th>
   <th>USER</th>
   <th>AGE</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>jhon@gmail.com</td>
   <td>jhon silva</td>
   <td>52</td>
  </tr>
  <tr>
   <td>marygirl@yahoo.com</td>
   <td>mary stu</td>
   <td>30</td>
  </tr>
  <tr>
   <td>cha24@yahoo.com</td>
   <td>charles steven</td>
   <td>63</td>
  </tr>
 </tbody>
</table>

Step 2: Define CSS classes

body{
 background:white!important;
}
td,tr,th{
 border:1px solid gray;
 border-collapse: collapse;
}
table{
 border-collapse: collapse;
}
input{
 margin-bottom:5px;
}
.clearFilter{
 padding:5px;
 cursor:pointer;
}

Step 3: Define the functions in javascript

//Function for filter and hightlight the results
function filterAndHightlight() {

 // Declare variables
 var input = document.querySelector("input");
 var filter = input.value.toUpperCase();
 var table = document.querySelector("table");
 var tr = table.getElementsByTagName("tr");
 var bgColor = 'yellow';
 var txtColor = 'black';

 // Loop through all table rows, and hide those who don't match the search query
 for (var i = 1; i < tr.length; i++) {

  //get all tds
  var tds = tr[i].querySelectorAll('td');
  var flagFound = false;

  //Loop through all tds in this row
  for(var e = 0; e < tds.length; e++){

   //get data from the cell
   var txtValue = tds[e].textContent || tds[e].innerText;
   var copyVal = tds[e].textContent || tds[e].innerText

   if(filter != ''){
    var index = txtValue.toUpperCase().indexOf(filter);

    if (index > -1) {
     flagFound = true;

     tds[e].innerHTML = copyVal.substring(0,index) +
     "<span style='background-color:"+bgColor+";color:"+txtColor+"'>" +
     copyVal.substring(index,index+input.value.length) + "</span>" +
     copyVal.substring(index + input.value.length);
    } else { 
     tds[e].innerHTML = copyVal;
    }
   } else {
    flagFound = true;
    tds[e].innerHTML = copyVal; 
   }
  }

  //hiding or showing row
  if(flagFound == true){
   tr[i].style.display = "";
  } else {
   tr[i].style.display = "none";
  }
 }
}

//Function for clear the filter
function clearFilter(){
 document.querySelector("input").value = "";
 filterAndHightlight();
}

👉 Notice that it will work no matter if it is uppercase or lowercase.

Check a working demo for this code:

SEE DEMO RATE THIS ARTICLE
4.4
17
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com