">
" />
Easy Tutorial
❮ Remainder And The Modulo Programmer Joke 18 ❯

JavaScript Table Data Search

Category Programming Techniques

This article introduces how to implement a table data search feature.

HTML Code:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">City</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Berglunds snabbkop</td>
    <td>Sweden</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Koniglich Essen</td>
    <td>Germany</td>
  </tr>
</table>

CSS Code:

#myInput {
    background-image: url('https://static.tutorialpro.org/images/mix/searchicon.png'); /* Search icon */
    background-position: 10px 12px; /* Positioning the search icon */
    background-repeat: no-repeat; /* Do not repeat the image */
    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 {
    /* Add border to table */
    border-bottom: 1px solid #ddd; 
}

#myTable tr.header, #myTable tr:hover {
    /* Add background color to header and rows on hover */
    background-color: #f1f1f1;
}

JavaScript Code:

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those that don't match the search query
  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";
      }
    } 
  }
}

Tip: If you need case sensitivity, you can remove the toUpperCase() method.

Tip: If you need to search the second column (City), you can change tr[i].getElementsByTagName('td')[0] to [1]. The index starts from 0, where 0 is the first column, 1 is the second column, and so on.

Live Demo

❮ Remainder And The Modulo Programmer Joke 18 ❯