Autocomplete Input Using JavaScript

Autocomplete Input Using JavaScript
Code Snippet:Vanilla Javascript Autocomplete
Author: bev
Published: May 2, 2024
Last Updated: May 2, 2024
Downloads: 64
License: MIT
Edit Code online: View on CodePen
Read More

This code enables autocomplete functionality for a search input field using JavaScript. It suggests text as you type. The `search` function filters matching strings from a predefined list. When you type, it dynamically updates the suggestions based on your input. Clicking on a suggestion fills the input with the selected text.

You can use this code in web projects that require a user-friendly search experience. It enhances user interaction by providing real-time suggestions. Implementing it saves time for users and improves the overall usability of your website.

How to Create Autocomplete Input Using Javascript

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. Set up your HTML structure. Create a div with a class of search-container and an input field inside it. Additionally, add a ul element inside a div with a class of suggestions to display the autocomplete suggestions.

<div class="search-container">
	<input type="text" name="fruit" id="fruit" placeholder="Search fruit">
	<div class="suggestions">
		<ul></ul>
	</div>
</div>

3. Apply CSS styles to your input field to make it visually appealing. You can customize the width, height, background color, and other properties to match your website’s design.

* {
  box-sizing: border-box;
}

:focus {
  outline: #e65c00 auto 5px;
}

body {
  font-family: sans-serif;
  display: flex;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  background: #e65c00;
  background: linear-gradient(to right, #f9d423, #e65c00);
}

input {
  border: 0 none;
}

.search-container {
  width: 400px;
  position: relative;
}
.search-container input,
.search-container .suggestions {
  width: 100%;
}
.search-container input {
  background: rgba(255, 255, 255, 0.2);
  height: 60px;
  padding: 0 10px;
}
.search-container .suggestions {
  position: absolute;
  top: 60px;
}

ul {
  display: none;
  list-style-type: none;
  padding: 0;
  margin: 0;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.2);
  max-height: 200px;
  overflow-y: auto;
}
ul.has-suggestions {
  display: block;
}
ul li {
  padding: 10px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.2);
}
ul li:hover {
  background-color: #e65c00;
}

input {
  border-bottom: 2px solid #e65c00;
}

4. Add the following JavaScript code to your project. This code defines an array of fruit names and functions to handle searching and displaying suggestions.

const input = document.querySelector('#fruit');
const suggestions = document.querySelector('.suggestions ul');

const fruit = [ 'Apple', 'Apricot', 'Avocado', 'Banana', 'Bilberry', 'Blackberry', 'Blackcurrant', 'Blueberry', 'Boysenberry', 'Currant', 'Cherry', 'Coconut', 'Cranberry', 'Cucumber', 'Custard apple', 'Damson', 'Date', 'Dragonfruit', 'Durian', 'Elderberry', 'Feijoa', 'Fig', 'Gooseberry', 'Grape', 'Raisin', 'Grapefruit', 'Guava', 'Honeyberry', 'Huckleberry', 'Jabuticaba', 'Jackfruit', 'Jambul', 'Juniper berry', 'Kiwifruit', 'Kumquat', 'Lemon', 'Lime', 'Loquat', 'Longan', 'Lychee', 'Mango', 'Mangosteen', 'Marionberry', 'Melon', 'Cantaloupe', 'Honeydew', 'Watermelon', 'Miracle fruit', 'Mulberry', 'Nectarine', 'Nance', 'Olive', 'Orange', 'Clementine', 'Mandarine', 'Tangerine', 'Papaya', 'Passionfruit', 'Peach', 'Pear', 'Persimmon', 'Plantain', 'Plum', 'Pineapple', 'Pomegranate', 'Pomelo', 'Quince', 'Raspberry', 'Salmonberry', 'Rambutan', 'Redcurrant', 'Salak', 'Satsuma', 'Soursop', 'Star fruit', 'Strawberry', 'Tamarillo', 'Tamarind', 'Yuzu'];

function search(str) {
	let results = [];
	const val = str.toLowerCase();

	for (i = 0; i < fruit.length; i++) {
		if (fruit[i].toLowerCase().indexOf(val) > -1) {
			results.push(fruit[i]);
		}
	}

	return results;
}

function searchHandler(e) {
	const inputVal = e.currentTarget.value;
	let results = [];
	if (inputVal.length > 0) {
		results = search(inputVal);
	}
	showSuggestions(results, inputVal);
}

function showSuggestions(results, inputVal) {
    
    suggestions.innerHTML = '';

	if (results.length > 0) {
		for (i = 0; i < results.length; i++) {
			let item = results[i];
			// Highlights only the first match
			// TODO: highlight all matches
			const match = item.match(new RegExp(inputVal, 'i'));
			item = item.replace(match[0], `<strong>${match[0]}</strong>`);
			suggestions.innerHTML += `<li>${item}</li>`;
		}
		suggestions.classList.add('has-suggestions');
	} else {
		results = [];
		suggestions.innerHTML = '';
		suggestions.classList.remove('has-suggestions');
	}
}

function useSuggestion(e) {
	input.value = e.target.innerText;
	input.focus();
	suggestions.innerHTML = '';
	suggestions.classList.remove('has-suggestions');
}

input.addEventListener('keyup', searchHandler);
suggestions.addEventListener('click', useSuggestion);

The search function filters the fruit names based on the user’s input. It compares the input value with each fruit name and returns matching results.

Set up an event listener to detect when the user types in the input field. When the user types, the searchHandler function is triggered, which calls the search function and displays the matching suggestions.

The showSuggestions function dynamically updates the suggestions list based on the search results. It highlights the matching part of each suggestion and displays them in the suggestions dropdown.

That’s all! hopefully, you have successfully created an autocomplete input using JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment