<!-- 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}:`
              }
            }
        })
    })
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
  2. https://cdn.jsdelivr.net/npm/typeahead.js@0.11.1/dist/typeahead.bundle.min.js