Back

Building an Efficient Autocomplete Search Box

Step-by-step guide to creating a user-friendly autocomplete search input to streamline form entry.

HTML

To start with, create a simple structure for our autocomplete search input. We use a containing div to wrap our input and the suggestions list.
        <div class="autocomplete-container">
          <input type="text" id="autocomplete-input" class="search-input" placeholder="Search...">
          <div id="autocomplete-list" class="autocomplete-items"></div>
        </div>
      

Javascript

Our JavaScript code will manage the interaction between the user and the suggestions. We have a predefined list of suggestions for simplicity, but this could come from a server in typical web applications.
        const suggestions = ['Apple', 'Banana', 'Orange', 'Grapes', 'Pineapple', 'Strawberry', 'Watermelon', 'Blueberry', 'Raspberry', 'Mango'];

        document.getElementById('autocomplete-input').addEventListener('input', function() {
          let inputVal = this.value.toLowerCase();
          let list = document.getElementById('autocomplete-list');
          list.innerHTML = '';
          if (!inputVal) return false;
          suggestions.forEach(function(item) {
            if (item.toLowerCase().includes(inputVal)) {
              let matchItem = document.createElement('div');
              matchItem.innerHTML = `<strong>${item.substr(0, inputVal.length)}</strong>${item.substr(inputVal.length)}`;
              matchItem.innerHTML += `<input type='hidden' value='${item}'>`;
              matchItem.addEventListener('click', function() {
                document.getElementById('autocomplete-input').value = this.getElementsByTagName('input')[0].value;
                list.innerHTML = '';
              });
              list.appendChild(matchItem);
            }
          });
        });
      
We attach an event listener to the input field to capture keystrokes. Every time the input changes, we clear the previous list of suggestions. If the input field is not empty, we iterate over the suggestions array, checking for matches. Matches are added to the suggestions list. When a suggestion is clicked, it populates the input with that value and clears the suggestion list.

CSS

The CSS styles our input and suggestion list. We enhance input focus with a transition effect on the border, and organize the suggestions list with sufficient padding and hover effects for usability.
        .autocomplete-container {
          position: relative;
          display: inline-block;
        }

        .search-input {
          width: 100%;
          box-sizing: border-box;
          border: 1px solid #cccccc;
          outline: none;
          padding: 10px;
          border-radius: 5px;
          transition: border-color 0.3s ease;
        }

        .search-input:focus {
          border-color: #66afe9;
        }

        .autocomplete-items {
          position: absolute;
          border: 1px solid #d4d4d4;
          border-bottom: none;
          border-top: none;
          z-index: 99;
          top: 100%;
          left: 0;
          right: 0;
        }

        .autocomplete-items div {
          padding: 10px;
          cursor: pointer;
          background-color: #ffffff;
          border-bottom: 1px solid #d4d4d4;
        }

        autocomplete-items div:hover {
          background-color: #e9e9e9;
        }
      
Our primary focus here is ease of use and readability. The search bar becomes a dynamic tool displaying options which help users complete their search more efficiently.

Conclusion

This autocomplete search box enhances user experience by providing real-time search suggestions. Suitable for various applications like forms and search engines, this component reduces user input errors and speeds up data entry. Feel free to expand upon this foundation by connecting to a server for dynamic suggestions or adding accessibility features to make it suitable for a broader audience.

Whole code

<div class="autocomplete-container">
  <input type="text" id="autocomplete-input" class="search-input" placeholder="Search...">
  <div id="autocomplete-list" class="autocomplete-items"></div>
</div>

<script>
const suggestions = ['Apple', 'Banana', 'Orange', 'Grapes', 'Pineapple', 'Strawberry', 'Watermelon', 'Blueberry', 'Raspberry', 'Mango'];

document.getElementById('autocomplete-input').addEventListener('input', function() {
  let inputVal = this.value.toLowerCase();
  let list = document.getElementById('autocomplete-list');
  list.innerHTML = '';
  if (!inputVal) return false;
  suggestions.forEach(function(item) {
    if (item.toLowerCase().includes(inputVal)) {
      let matchItem = document.createElement('div');
      matchItem.innerHTML = `<strong>${item.substr(0, inputVal.length)}</strong>${item.substr(inputVal.length)}`;
      matchItem.innerHTML += `<input type='hidden' value='${item}'>`;
      matchItem.addEventListener('click', function() {
        document.getElementById('autocomplete-input').value = this.getElementsByTagName('input')[0].value;
        list.innerHTML = '';
      });
      list.appendChild(matchItem);
    }
  });
});
</script>

<style>
.autocomplete-container {
  position: relative;
  display: inline-block;
}

.search-input {
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #cccccc;
  outline: none;
  padding: 10px;
  border-radius: 5px;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  border-color: #66afe9;
}

.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  top: 100%;
  left: 0;
  right: 0;
}

.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #ffffff;
  border-bottom: 1px solid #d4d4d4;
}

autocomplete-items div:hover {
  background-color: #e9e9e9;
}
</style>
      
Thank you for reading this article.

Comments

More inputs

Similar

See also