Implementing jquery UI autocomplete to show suggestions when you type “@”

前端 未结 3 1674
生来不讨喜
生来不讨喜 2020-11-30 02:38

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.

3条回答
  •  渐次进展
    2020-11-30 03:27

    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.

提交回复
热议问题