Search and filter on a HTML table using javascript


Mar 17, 2019

Real time search and filter on a HTML table using javascript Its a common practice to display large data using table elements. Moreover, many a times its helpfull to search through the displayed data especially when there are lots of rows and columns. One cannot expect users to keep scrolling page for finding information from the table. In this artical I will show you an easy way to search through a html table using JavaScript.

CSS Code:


* {
  box-sizing: border-box;
}
.wrapper{
width:60%;
margin:auto
}
#search-input {
  width: 100%;
  font-size: 16px;
  padding: 12px 30px;
  border: 1px solid #ccc;
  margin-bottom: 15px;
}

#tbl-container {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ddd;
  font-size: 18px;
}

#tbl-container th, #tbl-container td {
  text-align: left;
  padding: 12px;
}

#tbl-container tr {
  border-bottom: 1px solid #ddd;
}

#tbl-container tr.header, #tbl-container tr:hover {
  background-color: #f1f1f1;
}

HTML Code:


<div class="wrapper">

<input type="text" id="search-input" onkeyup="myFunction()" placeholder="Search here" title="Search">

<table id="tbl-container">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Country</th>
  </tr>
  <tr>
    <td>The Taj Mahal</td>
    <td>India</td>
  </tr>
  <tr>
    <td>Christ the Redeemer</td>
    <td>Brazil</td>
  </tr>
  <tr>
    <td>Petra</td>
    <td>Jordan</td>
  </tr>
  <tr>
    <td>The Great Wall of China</td>
    <td>China</td>
  </tr>
  <tr>
    <td>The Colosseum</td>
    <td>Rome</td>
  </tr>
  <tr>
    <td>Machu Picchu</td>
    <td>Peru</td>
  </tr>
  <tr>
    <td>Chichen Itza</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td>Paris specialites</td>
    <td>France</td>
  </tr>
</table>
</div>

JS Code:


function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("search-input");
  filter = input.value.toUpperCase();
  table = document.getElementById("tbl-container");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
  var abc = 0;
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) == 0) {
        abc = 1;
      } else {
       // tr[i].style.display = "none";
      }
    } 
    td1 = tr[i].getElementsByTagName("td")[1];
    if (td1) {
      txtValue = td1.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) == 0) {
        abc = 1;
      } else {
        //tr[i].style.display = "none";
      }
    }
    if (abc == 1) {
        tr[i].style.display = "";
      }
      else
      {
      tr[i].style.display = "none";
      }
  }
}

Copyright 2018. All rights are reserved