Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

jquery - autocomplete in middle of text (like Google Plus)

There are tons of options out there for doing autocompletion. Most of them seem to work on the first few letters that are typed.

In Google Plus, an autocomplete option drops down soon after typing @, no matter where it occurs in the form field, and uses the letters immediately following @ to guide the autocomplete. (It also looks quite nice!)

Has anybody shared code to do this sort of thing?

Does anybody have any pointers for trying to implement a toy version of this (e.g. in jQuery)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is possible with jQueryUI's autocomplete widget. Specifically, you can adapt this demo to satisfy your requirement. Here's an example:

function split(val) {
    return val.split(/@s*/);
}

function extractLast(term) {
    return split(term).pop();
}

var availableTags = [ ... ]; // Your local data source.

$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
        event.preventDefault();
    }
}).autocomplete({
    minLength: 0,
    source: function(request, response) {
        var term = request.term,
            results = [];
        if (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            }
        }
        response(results);
    },
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function(event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join("");
        return false;
    }
});

And here it is working: http://jsfiddle.net/UdUrk/

Let me know if you need any more information (such as how to make it work with a remote datasource).

Update: Here's an example using a remote datasource (StackOverflow's API): http://jsfiddle.net/LHNky/. It also includes custom display of autocomplete suggestions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...