Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML input autofill placeholder

What is the best approach to show the user suggestions when he writes into a textbox? I have all possible values in a JS array. Take as an example the array ["TYPO3", "Javascript"]. Now if the user enters the starting characters of such a string, he should get a suggestion like this: typo3 suggestion

I'm well aware of the placeholder html5 tag, but this would work only if the textbox is empty. I also know of the Datalist element or jQuery autocomplete but these only allow specific values. I also want content in my textbox that isn't predefined.

My idea would be to add a <span> tag right after the cursor, alter its content upon a input keyup event and move the span to the place where the cursor currently is. This would also make it possible for me to style the suggestion text.

But for me this seems to be a bad hack, so is there a cleaner solution for that?

like image 954
Elektropepi Avatar asked Nov 15 '25 22:11

Elektropepi


1 Answers

I can't tell you what is the best approach, but if you trust Google's approach, then their solution is pretty simple:

  • Have a regular text box (<input type='text' ...>) for the actual input.
  • A sibling <input> element which is disabled.

The actual text box should be on top of the disabled one. When the user starts typing and you found a match for the autocomplete, the suggested text should become the value of the other disabled input element (the text of the suggestion should be in a silver color).

Here's a small example: https://jsfiddle.net/e3L93o7g/

like image 105
Catalyst Avatar answered Nov 17 '25 20:11

Catalyst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!