HTML Input Auto-complete suggestion with Tab Completion (HTML + Vue.js + CSS)

Chetan Bansal
3 min readJul 6, 2019

There are all kinds of auto-complete libraries available around the web, which are really easy to plug-in and ready to use, but I came across a requirement which needed some digging, so I planned to share it with the community.

This is what we will be building in this article. When the user types the email in the input box, we will suggest them with an email extensions such as ‘gmail.com’, ‘yahoo.com’, ‘hotmail.com’, ‘aol.com’, ‘live.com’, ‘outlook.com’ and so on. The user can auto-complete the suggestion by pressing ‘Tab’.

NOTE: Don’t be afraid to go ahead with this article in case you are not familiar with Vue.js. The purpose of this article is not to teach how to CODE but to explain how to achieve the solution for this problem. Also, this might not be the only solution to this problem.

Before we dig in, we first need to understand the challenges behind this so that we can tackle them one-by-one.

  1. How to keep HTML input placeholder active even after the user types in the input box
  2. How to keep placeholder always updated with the user input.
  3. How to keep placeholder always to the right of user input.

These were the first few thoughts that came to my mind before developing the solution. So lets break this down.

  1. Default behavior of input box placeholder is that is becomes hidden as soon as user types in. So, to tackle this, we can use another input box with a placeholder value and display it only when there is a valid suggestion. (Refer figure below — Part B)
  2. To keep the placeholder value updated, if you are familiar with Vue.js or with any other reactive JS frameworks (React.js, Angular.js, Vue.js), your life becomes easier here. We can easily bind any attribute with a value that reactively changes on the UI.
  3. To keep the placeholder always to the right of input text, since there is no default functionality to get the position of input cursor and then bind the position of placeholder to the right of that position, we will use an extra hidden ‘div’ to maintain that space needed. (Refer figure below — Part C)
A — Original Input, B — Input with placeholder, C — div to maintain space for placeholder

Now we just need to use some CSS to keep (B) and (C) perfectly below (A), where (C) is always hidden and (B) is displayed only when there is a valid suggestion.

To summarize:-

  1. Keep (C’s) div content always updated with the current value of (A). This helps us maintain the left margin space for the placeholder suggestion.
  2. Keep (B’s) placeholder updated with a valid suggestion

Now you are ready to dig into the code behind this.

I hope someone gets benefit out of this.

In case of any queries or suggestions, you can get in touch with me in the comments section below and I will try me best to provide my inputs.

--

--