forked from netology-code/bhj-homeworks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.js
More file actions
95 lines (79 loc) · 3.04 KB
/
task.js
File metadata and controls
95 lines (79 loc) · 3.04 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Autocomplete {
constructor(container) {
this.container = container;
this.input = container.querySelector('.autocomplete__input');
this.searchInput = container.querySelector('.autocomplete__search');
this.list = container.querySelector('.autocomplete__list');
this.valueContainer = container.querySelector('.autocomplete__value');
this.valueElement = container.querySelector(
'.autocomplete__text-content'
);
this.registerEvents();
}
registerEvents() {
this.valueContainer.addEventListener('click', (e) => {
this.searchInput.classList.add('autocomplete__search_active');
this.list.classList.add('autocomplete__list_active');
this.searchInput.value = this.valueElement.textContent.trim();
this.searchInput.focus();
this.onSearch();
});
this.searchInput.addEventListener('input', (e) => this.onSearch());
this.list.addEventListener('click', (e) => {
const { target } = e;
if (!target.matches('.autocomplete__item')) {
return;
}
const { textContent: text } = target,
{ id: value, index } = target.dataset;
this.onSelect({
index,
text,
value,
});
});
}
onSelect(item) {
this.input.selectedIndex = item.index;
this.valueElement.textContent = item.text;
this.searchInput.classList.remove('autocomplete__search_active');
this.list.classList.remove('autocomplete__list_active');
}
onSearch() {
const matches = this.getMatches(this.searchInput.value);
this.renderMatches(matches);
}
renderMatches(matches) {
const html = matches.map(
(item) => `
<li>
<span class="autocomplete__item"
data-index="${item.index}"
data-id="${item.value}"
>${item.text}</span>
</li>
`
);
this.list.innerHTML = html.join('');
}
getMatches(text) {
const optionsArray = [...this.input.options].map((option) => ({
text: option.text,
value: option.value,
}));
return optionsArray.filter(option => option.text.includes(text));
/*
TODO: этот метод нужно дописать
text - фраза, которую вводят в поле поиска
Метод должен вернуть массив.
Он формируется на основе списка опций select-элемента (this.input)
Подходящие опции - те, чей текст содержит то, что есть в аргументе text
Необходимо вернуть массив объектов со свойствами:
{
text: 'Содержимое <option>',
value: 'Содержимое атрибута value'
}
*/
}
}
new Autocomplete(document.querySelector('.autocomplete'));