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
436 views
in Technique[技术] by (71.8m points)

javascript - Implementing jquery UI autocomplete to show suggestions when you type "@"

I'm using jquery UI AutoComplete to allow users to tag friends using @mentions. By default, the autocomplete suggestions appear when as soon you put focus on the textbox. How can you make the suggestions appear only when you type "@"? This is the code I have so far:

var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            ];
$("#tags").autocomplete({
    source: availableTags,
    minLength: 0
});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can do this by providing a function to the source option of autocomplete:

var availableTags = [ /* Snip */];

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

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

$("#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 the user typed an "@": */
        if (term.indexOf("@") >= 0) {
            term = extractLast(request.term);
            /* If they've typed anything after the "@": */
            if (term.length > 0) {
                results = $.ui.autocomplete.filter(
                availableTags, term);
            /* Otherwise, tell them to start typing! */
            } else {
                results = ['Start typing...'];
            }
        }
        /* Call the callback with the results: */
        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;
    }
});

Here's a working example: http://jsfiddle.net/BfAtM/2/

Note that this is almost identical to this demo, except for the requirement for the user to type "@". That code is located inside the source option argument.

Hope that helps.


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

...