DEV Community

Cover image for AutoComplete with JS
Walter Nascimento
Walter Nascimento

Posted on

AutoComplete with JS

[Clique aqui para ler em português]

Let’s create an autocomplete so that clicking on an input displays a suggestion list

Code

First let’s create the interface, we’ll do something simple, using just HTML.

<div>
  <label for="input">Input</label>
  <input type="text" id="input" />
  <ul id="suggestions"></ul>
</div>
Enter fullscreen mode Exit fullscreen mode

We have a div and inside we have a label, an input and a ul, this input will be where we will type the information and when the information matches the list we have it will be displayed in ul

(function () {
  "use strict";
  let inputField = document.getElementById('input');
  let ulField = document.getElementById('suggestions');
  inputField.addEventListener('input', changeAutoComplete);
  ulField.addEventListener('click', selectItem);

  function changeAutoComplete({ target }) {
    let data = target.value;
    ulField.innerHTML = ``;
    if (data.length) {
      let autoCompleteValues = autoComplete(data);
      autoCompleteValues.forEach(value => { addItem(value); });
    }
  }

  function autoComplete(inputValue) {
    let destination = ["Italy", "Spain", "Portugal", "Brazil"];
    return destination.filter(
      (value) => value.toLowerCase().includes(inputValue.toLowerCase())
    );
  }

  function addItem(value) {
    ulField.innerHTML = ulField.innerHTML + `<li>${value}</li>`;
  }

  function selectItem({ target }) {
    if (target.tagName === 'LI') {
      inputField.value = target.textContent;
      ulField.innerHTML = ``;
    }
  }
})();
Enter fullscreen mode Exit fullscreen mode

We have four functions:

  • changeAutoComplete = In this function we will have the input values, we check if there is any text, we call the autocomplete function, with the return of the autocomplete function we do a loop and add the item using the additem() function;
  • autoComplete = In this function we have a target array and with the data passed we check if the typed text exists in some value of the target array, if it exists it is returned;
  • addItem = Here the received value is added directly to ul;
  • selectItem = This function is activated by clicking on the item list, thus directly choosing the selected item;

ready simple like that.

Demo

See below for the complete working project.

Youtube

If you prefer to watch it, see the development on youtube.

References:

https://www.alura.com.br/artigos/criando-um-autocomplete-com-javascript?gclid=CjwKCAiA9vOABhBfEiwATCi7GFd7L_NkceqRgAk4CYgsN1rANbWH12fb2zhYnRWEM7rmko74XgbIfBoCB1YQAvD_BwE


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Linkedin - WalterNascimentoBarroso

Discussion (6)

Collapse
jonrandy profile image
Jon Randy

Better would be to use the built-in <datalist> element which does the same thing, and has better functionality and accessbility

Collapse
lukeshiru profile image
LUKESHIRU

I came here to suggest the same thing. There's quite a few articles here in dev reimplementing datalist. It seems folks don't actually know about it or don't even google if there is a native solution before coding it. Best thing about datalist besides what you mentioned is that it doesn't need JS to work.

Collapse
walternascimentobarroso profile image
Walter Nascimento Author

Hi, thanks for the comment.

I've used <datalist> in some other projects, but I ended up needing to style the <datalist> and in a quick search I couldn't figure out how to do it and I ended up creating this solution, but if you have an article that explains how to do it, I really appreciate if you share, so the next time I need it I'll have a better solution.

thanks ;)

Collapse
walternascimentobarroso profile image
Walter Nascimento Author

Hi, thanks for the comment.

I know the element but I couldn't style it (CSS) and I had a task where I needed to style the autocomplete, so my base solution was like this, this way it's easy to apply styles.

Collapse
dracon profile image
Wolfgang Born

I agree with all of the comments. If it is necessary to add som style or even icons or title and descriptions , the native datalist doesn't support styling and not select boxes with options either.
Walter's solution is quite simple, but you can style it as you wish.
Good job!

Collapse
walternascimentobarroso profile image
Walter Nascimento Author

thanks for the comment.