-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchBar.js
More file actions
75 lines (67 loc) · 1.76 KB
/
searchBar.js
File metadata and controls
75 lines (67 loc) · 1.76 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
const OPTIONS = [
{ name: "♥♥"},
{ name: 'CA'},
{ name: 'AZ'},
{ name: 'WA'},
{ name: 'NY'},
{ name: 'OR'},
{ name: 'TX'},
{ name: 'TS'},
{ name: 'ML'},
{ name: 'MX'},
];
const list = document.getElementById("list");
function setList(group){
clearList();
for (const keyword of group){
const item = document.createElement("li");
//item.classList.add('list-group-item');
const text = document.createTextNode(keyword.name);
item.appendChild(text);
list.appendChild(item);
}
if(group.length === 0){
setNoResult();
}
}
function clearList(){
while(list.firstChild){
list.removeChild(list.firstChild);
}
}
function setNoResult(){
const item = document.createElement("li");
//item.classList.add('list-group-item');
const text = document.createTextNode('No result found');
item.appendChild(text);
list.appendChild(item);
}
let searchInput = document.getElementById('search');
/*
searchInput == null
because js file should put at end of the HTML file!!!!!!
*/
function getRelevancy(value, Term){
if (value === Term){
return 2;
} else if (value.startsWith(Term)){
return 1;
} else if (value.includes(Term)){
return 0;
} else {
return -1;
}
}
searchInput.addEventListener('input', (event) => {
let value = event.target.value;
if(value && value.trim().length > 0){
value = value.trim().toUpperCase();
setList(OPTIONS.filter(key => {
return key.name.includes(value);
}).sort((keyA, keyB) => {
return getRelevancy(keyB.name, value) - getRelevancy(keyA.name, value);
}));
}else{
clearList();
}
});