Easy Tutorial
❮ Android Tutorial Typeface Strlen And Sizeof ❯

JavaScript/CSS List Search Functionality

Category Programming Technology

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

First, take a look at the effect:

View online example: https://c.tutorialpro.org/codedemo/6227/

Basic HTML Code

Example

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

<ul id="myUL">
  <li><a href="#">Google</a></li>
  <li><a href="#">tutorialpro</a></li>

  <li><a href="#">Taobao</a></li>
  <li><a href="#">Wiki</a></li>

  <li><a href="#">Facebook</a></li>
  <li><a href="#">Zhihu</a></li>
  <li><a href="#">Weibo</a></li>
</ul>

Note: In the example, href="#" is used to represent a link, which should be replaced with your own links in actual projects.

Here is the style for the search box and suggestion menu:

Example

#myInput {
  background-image: url('/css/searchicon.png'); /* Add search icon */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}

#myUL {
  /* Remove default list styling */
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#myUL li a {
  border: 1px solid #ddd; /* Add a border to all links */
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6; /* Grey background color */
  padding: 12px; /* Add some padding */
  text-decoration: none; /* Remove default text underline */
  font-size: 18px; /* Increase the font-size */
  color: black; /* Add a black text color */
  display: block; /* Make it into a block element to fill the whole list */
}

#myUL li a:hover:not(.header) {
  background-color: #eee; /* Add a hover effect to all links, except for headers */
}

Here is the JavaScript code for the search box and suggestion menu:

Example

function myFunction() {
  // Declare variables
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

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

** Click to Share Notes

Cancel

-

-

-

❮ Android Tutorial Typeface Strlen And Sizeof ❯