Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / 19+ JavaScript Autocomplete Dropdown Sample & Tutorial

19+ JavaScript Autocomplete Dropdown Sample & Tutorial

January 22, 2024January 11, 2024 by Asif Mughal
JavaScript Autocomplete Dropdown
Share This:
Code Snippet:Vanilla Javascript Autocomplete
Author: Beverly Cheak
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 24,878
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This Vanilla JavaScript code snippet helps you to create autocomplete suggestion dropdown. It uses JavaScript regular expression pattern to match the entered value on keyup event. After matching, it appends the result to the suggestions list and highlights both the first letter and all matches in the suggested keywords.

You just need to update your keywords in the array according to your select menu. Then this plugin will search and load the relevant result in the suggestions list. Besides this, you can customize/style the select dropdown with additional CSS according to your needs.

How to Create JavaScript Autocomplete Dropdown

1. First of all, create a div element with the class name “search-container” and place an input element for the search box. Likewise, create a div element just after the input and define its class name “suggestions”. Place an unordered list (ul element) inside the suggestions dropdown, it will contain the search items. So, the complete HTML structure for the autocomplete dropdown is as follows:

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

2. After creating the HTML, we need to style the input box and suggestions dropdown list. So, add the following CSS styles to your project. You can also use your own CSS styles in order to customize the autocomplete dropdown according to your existing website template.

input {
  border: 0 none;
}

.search-container {
  width: 400px;
  position: relative;
  margin: 15px auto;
}
.search-container input,
.search-container .suggestions {
  width: 100%;
  background: #fff;
  text-align: left;
}
.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;
}

3. Finally, add the following autocomplete dropdown function between the <script> before closing the body tag. In the below function, you just need to update fruit array values. You can read more about JavaScript arrays that may help in regards to defining your own values.

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);

That’s all! hopefully, you have successfully integrated this code snippet into your project to create autocomplete dropdown. If you have any questions or facing any issues, feel free to comment below.

Similar Code Snippets:

  • JavaScript Avatar Generator

    JavaScript Avatar Generator

  • Background Image Slideshow using JavaScript

    Background Image Slideshow using JavaScript

  • 3D carousel slider JavaScript

    3D carousel slider JavaScript

  • Find Duplicates in Array JavaScript

    Find Duplicates in Array JavaScript

  • Silky Smooth Checkbox Toggles Using SVG.js

    Silky Smooth Checkbox Toggles Using SVG.js

  • Floating Words Animation Using Vanilla JavaScript

    Floating Words Animation Using Vanilla JavaScript

  • CSS Image Filter Editor in JavaScript

    CSS Image Filter Editor in JavaScript

  • JavaScript Detect Media Query Change

    JavaScript Detect Media Query Changes

  • Drum Kit Using JavaScript

    Drum Kit Using JavaScript

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Text & Input, Vanilla JavaScript Tags Select Dropdown
Pure CSS Stylish Dropdown Menu
Simple Tabs in HTML CSS and JavaScript

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,396 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,933 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,948 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,357 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,034 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,103 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,392 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,388 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,145 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,199 views

Advertisement

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

Please Rel0ad/PressF5 this page if you can't click the download/preview link

F5
X