Ok, here is an example which fetches a JSON file containing 1000 employees. Maybe this is an option?
[
{"id":1,"first_name":"Keven","last_name":"Insole"},
{"id":2,"first_name":"Carolann","last_name":"D'Hooge"},
{"id":3,"first_name":"Shepherd","last_name":"Di Maggio"},
...
]
It could obviously be fetched from an api instead.
As per some previous examples I have posted here on Sitepoint, I am using autocomplete.js
The setup as follows
HTML
<div class='container'>
<form id='search-form' class='search-form' action=''>
<h3 class='form-title'>Employees</h3>
<input
type='search'
id='name'
name='search_term'
dir='ltr'
spellcheck=false
tabindex='1'
aria-label='enter full name'
placeholder='full name'
>
<!-- where autocomplete outputs a list to -->
<datalist id='names'></datalist>
</form>
<output id='employee'></output>
</div>
Javascript
// generic function for fetching json data from a url
const fetchJson = async (url) => {
try {
const response = await fetch(url);
return response.json();
} catch (err) {
console.error(err);
}
}
async function main() {
const employees = await fetchJson('https://assets.codepen.io/3351103/employees.json');
// Using the employees JSON data: [{"id":1,"first_name":"Keven","last_name":"Insole"}, ...]
// Create a new array of objects joining "first_name" and "last_name" to make a "fullName" property
// include employee "id".
const employeesSearchData = employees.map((employee) => {
return {
id: employee.id,
fullName: `${employee['first_name']} ${employee['last_name']}`
};
});
const autoCompleteJS = new autoComplete({
selector: "#name",
data: {
src: employeesSearchData,
keys: ['fullName'] // key to use for search
},
threshold: 2,
resultsList: { maxResults: 10 },
resultItem: { highlight: true },
events: {
input: {
selection(event) {
// e.g. {id: 575, fullName: 'Rutherford Dobbie'}
const employee = event.detail.selection.value;
autoCompleteJS.input.value = employee.fullName;
// for illustration purposes
document.querySelector('#employee')
.textContent = `ID: ${employee.id}, Name: ${employee.fullName}`
}
},
}
});
// Clear employee, when search is cleared.
document.querySelector('#name').addEventListener('input', (event) => {
if (!event.target.value) {
document.querySelector('#employee').textContent = ""
}
})
}
main();
Information on using the fetch api