xxxxxxxxxx
1
<div id="basic" class="form-outline" data-mdb-input-init>
2
<input type="text" id="form11" class="form-control form-icon-trailing" />
3
<label class="form-label" for="form1">Example label</label>
4
<span class="trailing pe-auto clear d-none" tabindex="0">✕</span>
5
</div>
xxxxxxxxxx
1
.trailing.clear {
2
cursor: pointer;
3
z-index: 999;
4
5
&:focus {
6
color: #3b71ca;
7
outline: none;
8
}
9
}
xxxxxxxxxx
1
const basicAutocomplete = document.querySelector('#basic');
2
const form11 = document.querySelector("#form11");
3
const clearButton = document.querySelector('.trailing.clear');
4
const data = ['One', 'Two', 'Three', 'Four', 'Five'];
5
6
const dataFilter = (value) => {
7
return data.filter((item) => {
8
return item.toLowerCase().startsWith(value.toLowerCase());
9
});
10
};
11
12
const autocomplete = new mdb.Autocomplete(basicAutocomplete, {
13
filter: dataFilter
14
});
15
16
const showElement = (element) => {
17
if (element.classList.contains('d-none')) {
18
element.classList.remove('d-none');
19
}
20
}
21
22
const hideElement = (element) => {
23
if (!element.classList.contains('d-none')) {
24
element.classList.add('d-none');
25
}
26
}
27
28
const clearInput = (button) => {
29
const evt = document.createEvent("HTMLEvents");
30
evt.initEvent("blur", false, true);
31
32
const input = button.parentNode.querySelector(".form-icon-trailing");
33
input.value = null;
34
input.dispatchEvent(evt);
35
autocomplete.search("")
36
hideElement(button);
37
}
38
39
clearButton.addEventListener('click', () => clearInput(clearButton));
40
clearButton.addEventListener('keydown', (event) => {
41
if (event.code === "Enter") {
42
event.preventDefault();
43
clearButton.click();
44
}
45
});
46
47
48
form11.addEventListener('input', () => {
49
if (form11.value !== null) {
50
showElement(clearButton);
51
}
52
});
53
54
basicAutocomplete.addEventListener('itemSelect.mdb.autocomplete', () => {
55
if (form11.value !== null) {
56
showElement(clearButton);
57
}
58
});
59
Console errors: 0