Searchable List In HTML Javascript (Simple Example)

Need to add a “search feature” to a list on your website? A “simple version” can literally be done with like… less than 15 lines of Javascript code. No kidding – Let’s go!

 

CODE DOWNLOAD

I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

 

 

VIDEO TUTORIAL

 

EXAMPLE 1) JAVASCRIPT SEARCHABLE LIST

1A) THE DEMO

Take note – This demo is case-sensitive.

  • Alpaca
  • Bird
  • Camel
  • Dog
  • Elk
  • Ferret
  • Gazelle
  • Hare
  • Ibex

 

 

1B) THE HTML

1-search.html
<!-- (PART A) SEARCH FOR -->
<input type="text" id="sfor" placeholder="Search">
 
<!-- (PART B) SEARCH LIST -->
<ul id="slist">
  <li>Alpaca</li> <li>Bird</li> <li>Camel</li>
  <li>Dog</li> <li>Elk</li> <li>Ferret</li>
  <li>Gazelle</li> <li>Hare</li> <li>Ibex</li>
</ul>
  • <ul id="slist"> Your “usual list of items”.
  • <input type="text" id="sfor"> Just add a “search for” box, and that’s all.

 

 

1C) JAVASCRIPT – CASE SENSITIVE LIST SEARCH

1-search-sensitive.js
window.addEventListener("load", () => {
  // (PART A) GET SEARCHABLE LIST
  const sfor = document.getElementById("sfor"),
        slist = document.querySelectorAll("#slist li");
 
  // (PART B) SEARCH & FILTER LIST AS USER TYPES
  sfor.onkeyup = () => {
    for (let i of slist) {
      i.style.display = i.innerHTML.indexOf(sfor.value) == -1 ? "none" : "list-item";
    }
  };
});
  1. On window load, get the search box and all the list items.
  2. As the user types in the “search for” box:
    • Loop through all the list items.
    • If the list item contains the search term show it.
    • Else hide the list items that don’t match.

 

 

1D) JAVASCRIPT – CASE INSENSITIVE LIST SEARCH

1-search-insensitive.js
window.addEventListener("load", () => {
  // (PART A) GET SEARCHABLE LIST
  const sfor = document.getElementById("sfor"),
        slist = document.querySelectorAll("#slist li");
 
  // (PART B) SEARCH & FILTER LIST AS USER TYPES
  sfor.onkeyup = () => {
    const search = sfor.value.toLowerCase();
    for (let i of slist) {
      i.style.display = i.innerHTML.toLowerCase().indexOf(search) == -1 ? "none" : "list-item";
    }
  };
});

If you prefer case-insensitive search, it only requires 2 small changes:

  • search = sfor.value.toLowerCase() Change to user’s search term to all lower case.
  • i.innerHTML.toLowerCase().indexOf(search) Do the list items search in all lower case.

 

 

EXAMPLE 2) AJAX SEARCHABLE LIST

2A) THE HTML

2-ajax-search.html
<!-- (PART A) SEARCH FOR -->
<input type="text" id="sfor" placeholder="Search">
 
<!-- (PART B) SEARCH LIST -->
<ul id="slist"></ul>
  • Take note, the list is now empty.
  • This example will do the search and load the list items from the server instead.

 

 

2B) THE JAVASCRIPT

2-ajax-search.js
// (PART A) SEARCH LIST VIA AJAX
function dosearch () {
  // (A1) GET SEARCH TERM
  var data = new FormData();
  data.append("search", document.getElementById("sfor").value);
 
  // (A2) SEND DATA TO SERVER
  fetch("2-ajax-search.php", { method: "POST", body: data })
  .then(res => res.json())
  .then(res => {
    // (A2-1) EMPTY LIST
    let slist = document.getElementById("slist");
    slist.innerHTML = "";
 
    // (A2-2) REBUILD LIST
    res.forEach(i => {
      let li = document.createElement("li");
      li.innerHTML = i;
      slist.appendChild(li);
    });
  });
}
 
// (PART B) INITIALIZE SEARCHABLE LIST
window.addEventListener("load", () => {
  dosearch();
  sfor.onkeyup = dosearch;
});

Slightly more long-winded in this one:

  • (A) function dosearch() will pass the search term to the server, fetch and draw the HTML list items.
  • (B) On window load, run dosearch() to initialize the list. Also run it everytime the user types in the search box.

How dosearch() works:

  • (A1) Get the search term from the text field.
  • (A2) Send the search term to the server via POST.
  • (A2-1 & A2-2) The server returns a list of items in JSON. Simply loop through and rebuild the HTML list.

 

 

2C) SERVER-SIDE SEARCH

2-ajax-search.php
<?php
// (PART A) DATA ARRAY
$data = [
  "Alpaca", "Bird", "Camel",
  "Dog", "Elk", "Ferret",
  "Gazelle", "Hare", "Ibex"
];
 
// (PART B) SEARCH DATA
if (isset($_POST["search"]) && $_POST["search"]!="") {
  $search = [];
  foreach ($data as $d) {
    if (str_contains($d, $_POST["search"])) { $search[] = $d; }
  }
} else { $search = $data; }
 
// (PART C) OUTPUT RESULTS
echo json_encode($search);

Lastly, a short and simple PHP server-side example:

  1. The list of items in an array.
  2. Pretty much the same as the previous Javascript example – Loop through the list items and match against the user’s search term.
  3. Return the search results in JSON format. This will be picked up in the Javascript (A2) to draw the HTML list.

P.S. In a “proper project”, the server-side will most likely run a database search and return the relevant results.

P.P.S. This PHP example is also case-sensitive. If you want case-insensitive, do the same “convert search term and items to all lower case”.

 

 

THE END – TO AJAX OR NOT TO AJAX?

For the beginners who are confused:

  • Just stick with the “non-AJAX” version if the list is short or “still somewhat manageable”.
  • It is only when there are too many items to display that we use AJAX to manage it – Save the items into a database, do a database search in the server-side script, along with limiting the total number of search results.

 

CHEAT SHEET

Searchable List In HTML Javascript (click to enlarge)