2

I'm implementing autocomplete on my site. However, I don't like how you have to "click" the suggestion to get it into the form field.

I would like gray text to show up suggesting the rest of the search term, like Google does. If the user hits tab then that search term shows up and the user can hit enter.

Casey
  • 2,611
  • 6
  • 34
  • 60

2 Answers2

3

Here is my solution. The code is written quickly and should be considered only as an example.

HTML:

<div id="inp">
    <input type="text" id="search" value="" />
    <span id="ending" style="color: gray" ></span>
</div>

JS:

$( "#search" ).autocomplete({
    source: availableTags,
    //catch open event
    open: function(event, ui) {
        //get first item in opened list
        var firstInList = $(".ui-autocomplete").children('li').children('a').html();
        //find the difference and assign to span
        $('#ending').html(firstInList.substring(this.value.length))
    }
});

$('#search').keypress(function(e){
    var keyCode = e.keyCode || e.which;
    //if Tab
    if (keyCode == 9) {
        e.preventDefault();
        //get first item in list and assign to input
        $(this).val($(".ui-autocomplete").children('li').children('a').html());
        $(".ui-autocomplete").hide();
        $('#ending').empty();
    }
    //input width
    this.style.width = ((this.value.length + 1) * 6) + 4 + 'px';
});

DEMO

Vitalii Maslianok
  • 1,601
  • 1
  • 14
  • 16
1

By using a contenteditable div instead of an input, the input field will resize immediately, without the latency caused by the event handler. Then just place a span at the end of the div with the suggested text.

Also, it appears that jQuery's autocomplete handler is quite slow compared to a straightforward implementation. This gives the following, quite smooth, result:

DEMO

There are some obvious pros and cons to not using an input field:

Pros

  • Immediate positioning of the autocomplete text
  • Clicking on the gray text, or to the right of it, directs you to the input field

Cons

  • Need to take care of paste and drag events, because you don't want HTML ending up in your form field. (I didn't do this in the Demo.)
  • Other issues with contenteditable fields, for example Clicking outside a contenteditable div stills give focus to it?
  • When used in a form, the content from the contenteditable element isn't submitted, so you need to take care of that.

To me, the zero-latency outweighs those cons.


One should note that there are many things I didn't properly take care of: what if a user somehow manages to focus inside or after the suggested text? (For example, by clicking slightly under it.) What if the user makes a selection starting at the input text and ending in the suggested text? It gets very complicated. I think this is why such autocomplete gray text is rarely seen.

user3187724
  • 218
  • 2
  • 12