Autocomplete (REST API)

In this example below you will see how to do a Autocomplete (REST API) with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by elaboratecon, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright elaboratecon ©
  • HTML
  • CSS
  • JavaScript
    <input type="text" id="search"></input>

/*Downloaded from https://www.codeseek.co/elaboratecon/autocomplete-rest-api-GdxVvx */
    


/*Downloaded from https://www.codeseek.co/elaboratecon/autocomplete-rest-api-GdxVvx */
    // DOM Elements
const search = document.getElementById('search');


function update() {
  this.query = this.quill.getText(this.atIndex + 1, sel - this.atIndex - 1).toLowerCase();
  var that = this;
  var sortedUsers = [];
  $.getJSON("https://jsonplaceholder.typicode.com/users", { "query": this.query, "hideGroups" : "true" }, function(data) {
    for(var i = 0; i < data.length; i++) {
      sortedUsers.push({
        id: data[i]['id'],
        name: data[i]['name']
      });
    }
    console.log(sortedUsers);
    // that.renderCompletions(sortedUsers);
  });
}

let lastQuery = ''
let timeout

function fetchUsers(e) {
  let query = search.value.toLowerCase()
  
    
  if (query !== lastQuery) {
    console.log(`lastQuery: ${lastQuery} | query: ${query}`)

    lastQuery = query
    if(timeout) clearTimeout(timeout)

    timeout = setTimeout(function() {
      console.warn(`DATA FETCHED for ${query}`)
      // fetch('https://jsonplaceholder.typicode.com/users/'+query)
      //   .then(response => response.json())
      //   .then(json => console.log(json))
    }, 400)
  }
}

// Event handler
search.addEventListener('keyup', fetchUsers)



Comments