<!-- https://www.sitepoint.com/community/t/typehead-ajax-not-populate-the-suggestion/393453/8 -->
<input
class="typeahead"
type="text"
placeholder="username"
id="userName"
>
const getByUserName = function (users = []) {
return function (name, callback) {
const matchedNames = users.flatMap(function(user) {
const foundUser = user.name.toLowerCase().includes(name.toLowerCase())
return (foundUser) ? [ user.name ] : []
})
callback(matchedNames)
}
}
fetch(`https://jsonplaceholder.typicode.com/users`)
.then((response) => response.json())
.then((users) => {
$("#userName").typeahead({
hint: true,
highlight: true,
minLength: 2
}, {
name: 'names',
limit: 10,
source: getByUserName(users),
templates: {
header: function(data) {
console.log(data)
return `Results for ${data.query} from ${data.dataset}:`
}
}
})
})
This Pen doesn't use any external CSS resources.