girlafraid
girlafraid

Reputation: 35

Add suggested result to jQuery UI autocomplete input?

I am attempting to expand the jQuery UI autocomplete to resemble that of Google's search field, where the remaining text in the top suggested result (i.e. anything that's not the request.term), is added to the end of the user entered string in a different color.

I had planned to do this by placing an identically sized transparent div behind the original input using relative positioning, and the top matched result placed in this div in a lighter color.

My question is, the correct way to access the matched results array. My approach being as follows (streamlined example):

$(function() {
    var tags = [
        "One",
        "Two",
        "Three"
    ];
    $("input").autocomplete({
        source: tags,
        open: function() {
            // var topResult = HOW TO ACCESS?
            $('#divForText').text(topResult);
        }
    });
});

Can anyone clarify how to access the first value in the matched results array?

Upvotes: 1

Views: 1676

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

Here's one way you could accomplish this:

$("input").autocomplete({
    source: function(request, response) {
        var filtered = $.ui.autocomplete.filter(tags, request.term)
            , first = filtered.length ? filtered[0] : null;

        if (first) {
            $("#divForText").text(first);
        } else {
            $("#divForText").empty();
        }

        response($.ui.autocomplete.filter(langs, request.term));
    }
});

Basically, this is using the version of source that takes a function as a parameter. That function simply uses the filter method that autocomplete uses internally, and then updates the content.

Here's a working example: http://jsfiddle.net/UGsHR/75/

Upvotes: 2

Related Questions