forked from lsvekis/JavaScript-Exercises-Book
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimple Text Autocomplete
More file actions
55 lines (55 loc) · 1.95 KB
/
Simple Text Autocomplete
File metadata and controls
55 lines (55 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!-- Objective: Create a simple text autocomplete feature. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Text Autocomplete</title>
<style>
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
top: 100%;
left: 0;
right: 0;
}
.autocomplete-item {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
.autocomplete-item:hover {
background-color: #e9e9e9;
}
</style>
</head>
<body>
<input id="autocompleteInput" type="text" name="myCountry" placeholder="Type something...">
<div id="autocompleteList" class="autocomplete-items"></div>
<script>
const suggestions = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape", "Honeydew"];
document.getElementById('autocompleteInput').addEventListener('input', function() {
const input = this.value;
const list = document.getElementById('autocompleteList');
list.innerHTML = '';
if (!input) return;
suggestions.filter(item => item.toLowerCase().startsWith(input.toLowerCase())).forEach(filteredItem => {
const div = document.createElement('div');
div.innerHTML = `<strong>${filteredItem.substr(0, input.length)}</strong>${filteredItem.substr(input.length)}`;
div.classList.add('autocomplete-item');
div.addEventListener('click', function() {
document.getElementById('autocompleteInput').value = filteredItem;
list.innerHTML = '';
});
list.appendChild(div);
});
});
document.addEventListener('click', function (e) {
document.getElementById('autocompleteList').innerHTML = '';
});
</script>
</body>
</html>