Skip to content
Advertisement

Show autocomplete only after 3 entered chars in field?

Is it possible to autocomplete only after a user entered at least 3 letters? Here is my current code:

HTML/PHP:

JavaScript

I only find some Code with Jquery, is it not possible to do this without jquery?

Is it even possible? Any ideas?

Advertisement

Answer

Here is a way to do it: removing the datalist ID attribute.

First, declare the querySelector() methods.

JavaScript

Then declare the addEventListener method on the input element.

JavaScript

Explanation

When the input value has a length greater than or equal to 2, the setAttribute() method sets the datalist ID attribute to "users".

I set the operator to >= 2 and not >= 3. Here is why: the datalist dropdown element is triggered at each keypress.

The process goes like this:

  1. length == 1 id="" – The drop down is not displayed, no ID is linked to the datalist;
  2. length == 2 id="users" – The drop down is not displayed, then datalist has its ID set to "users";
  3. length == 3 id="users" – The drop down now reads that the ID is set to "users" and displays the drop down.

Cons

  • Since the attribute is set when the input length is >= 2, if the input length == 3, the attribute will be removed when the input length == 2, and the drop down will be hidden when the input length == 1.
  • Since the drop down list is part of the OS and is not a DOM element, it cannot be styled (or hidden, in this case). This is why I used the setAttribute() method to set or remove the ID.

Upgrade?

A great upgrade / perfect solution would be creating a dropdown in JS just under the input. The drop down would be DOM element, and you could style it the way you want. You could ealisy display it > 2 chars and hide it < 3 chars.

Snippet

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement