ImplementJavaScript Auto Complete / Suggestion feature

JavaScript's auto-complete feature helps users by suggesting matching options as they type. This improves user experience and reduces typing errors. We can implement this using HTML5's datalist element combined with JavaScript for dynamic filtering.

Understanding the HTML Structure

The foundation uses an input field linked to a datalist element. The datalist contains predefined options that appear as suggestions:

<input type="text" list="datalist" class="fruits" />
<datalist id="datalist">
  <option value="apple"></option>
  <option value="orange"></option>
</datalist>

Complete Implementation

<!DOCTYPE html>
<html>
<head>
<style>
  body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    padding: 20px;
  }
  .fruits {
    padding: 8px;
    font-size: 16px;
    width: 300px;
    border: 2px solid #ddd;
    border-radius: 4px;
  }
</style>
</head>
<body>
<h1>JavaScript Auto Complete / Suggestion Feature</h1>
<p>Type a fruit name to see suggestions:</p>
<input type="text" list="datalist" class="fruits" placeholder="Enter fruit name..." />
<datalist id="datalist">
  <option value="apple"></option>
  <option value="banana"></option>
  <option value="guava"></option>
  <option value="litchi"></option>
  <option value="mango"></option>
  <option value="orange"></option>
  <option value="peach"></option>
  <option value="pineapple"></option>
  <option value="pomegranate"></option>
</datalist>

<script>
  const fruits = ["apple", "banana", "guava", "litchi", "mango", "orange", "peach", "pineapple", "pomegranate"];
  const input = document.querySelector(".fruits");
  const datalist = document.getElementById("datalist");

  input.addEventListener("keyup", function(event) {
    const inputValue = event.target.value.toLowerCase();
    
    // Clear existing options
    datalist.innerHTML = "";
    
    // Filter and add matching fruits
    fruits.forEach(fruit => {
      if (fruit.toLowerCase().includes(inputValue) && inputValue !== "") {
        const option = document.createElement("option");
        option.value = fruit;
        datalist.appendChild(option);
      }
    });
  });
</script>
</body>
</html>

How It Works

The script listens for keyup events on the input field. When users type, it:

  • Captures the current input value
  • Clears the datalist of previous suggestions
  • Filters the fruits array for matches using includes()
  • Dynamically creates new option elements for matching results

Enhanced Version with Custom Styling

For more control over appearance, you can create a custom dropdown instead of using datalist:

<!DOCTYPE html>
<html>
<head>
<style>
  .autocomplete-container {
    position: relative;
    width: 300px;
  }
  .autocomplete-input {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    border: 2px solid #ddd;
  }
  .suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #ddd;
    max-height: 200px;
    overflow-y: auto;
    display: none;
  }
  .suggestion-item {
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #eee;
  }
  .suggestion-item:hover {
    background-color: #f5f5f5;
  }
</style>
</head>
<body>
<h1>Custom Auto Complete</h1>
<div class="autocomplete-container">
  <input type="text" class="autocomplete-input" placeholder="Search fruits...">
  <div class="suggestions" id="suggestions"></div>
</div>

<script>
  const fruits = ["apple", "banana", "guava", "litchi", "mango", "orange", "peach", "pineapple", "pomegranate"];
  const input = document.querySelector('.autocomplete-input');
  const suggestionsDiv = document.getElementById('suggestions');

  input.addEventListener('input', function() {
    const value = this.value.toLowerCase();
    suggestionsDiv.innerHTML = '';
    
    if (value) {
      const matches = fruits.filter(fruit => 
        fruit.toLowerCase().includes(value)
      );
      
      if (matches.length > 0) {
        suggestionsDiv.style.display = 'block';
        matches.forEach(match => {
          const div = document.createElement('div');
          div.className = 'suggestion-item';
          div.textContent = match;
          div.onclick = () => {
            input.value = match;
            suggestionsDiv.style.display = 'none';
          };
          suggestionsDiv.appendChild(div);
        });
      } else {
        suggestionsDiv.style.display = 'none';
      }
    } else {
      suggestionsDiv.style.display = 'none';
    }
  });

  // Hide suggestions when clicking outside
  document.addEventListener('click', function(e) {
    if (!e.target.closest('.autocomplete-container')) {
      suggestionsDiv.style.display = 'none';
    }
  });
</script>
</body>
</html>

Key Features

  • Case-insensitive matching: Users can type in any case
  • Dynamic filtering: Suggestions update as users type
  • Click selection: Users can click suggestions to select them
  • Keyboard friendly: Works with browser's native datalist behavior

Browser Compatibility

The datalist element is supported in all modern browsers. For older browsers, consider using a JavaScript library like jQuery UI Autocomplete or implement a fully custom solution.

Conclusion

JavaScript auto-complete enhances user experience by providing real-time suggestions. The HTML5 datalist offers a simple solution, while custom implementations provide greater control over styling and behavior.

Updated on: 2026-03-15T23:18:59+05:30

162 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements