Easy Tutorial
❮ Restful Architecture Verilog2 Pli Intro ❯

JavaScript/CSS Table Search Functionality

Category Programming Techniques

In this section, we will learn how to implement search or filter functionality for a table using JS/CSS.

Let's first look at the effect as follows:

Check out the live example: https://c.tutorialpro.org/codedemo/6228/

Basic HTML Code

Example

<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%;">Url</th>
  </tr>
  <tr>
    <td>Google</td>
    <td>www.google.com</td>
  </tr>
  <tr>
    <td>tutorialpro</td>
    <td>www.tutorialpro.org</td>
  </tr>
  <tr>
    <td>Taobao</td>
    <td>www.taobao.com</td>
  </tr>
  <tr>
    <td>Baidu</td>
    <td>www.baidu.com</td>
  </tr>
</table>

The following are the styles for the search box and the suggestion menu:

Example

#myInput {
  background-image: url('/css/searchicon.png'); /* Add a search button */
  background-position: 10px 12px; /* Position the search button */
  background-repeat: no-repeat; /* Do not repeat the image */
  width: 100%; /* Display full screen */
  font-size: 16px; /* Font size */
  padding: 12px 20px 12px 40px; /* Set padding */
  border: 1px solid #ddd; /* Add a gray border */
  margin-bottom: 12px; /* Add margin at the top */
}

#myTable {
  border-collapse: collapse; /* Collapse borders */
  width: 100%; /* Display full screen */
  border: 1px solid #ddd; /* Set a gray border */
  font-size: 18px; /* Font size */
}

#myTable th, #myTable td {
  text-align: left; /* Align text to the left */
  padding: 12px; /* Set padding */
}

#myTable tr {
  /* Set a bottom border for each row */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header, #myTable tr:hover {
  /* Set a background for the table header */
  background-color: #f1f1f1;
}

The following is the JavaScript code for the search box and the suggestion menu:

Example

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  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 do not match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

Tip: If you want to perform a case-sensitive search, you can remove the toUpperCase() method.

Tip: If you want to search the second column, change [0] to [1].

Click to Share Notes

Cancel

-

-

-

❮ Restful Architecture Verilog2 Pli Intro ❯