autocomplete in middle of text (like Google Plus)
Asked Answered
S

5

11

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)?

Sharkey answered 17/8, 2011 at 7:47 Comment(2)
Sorry about that! Done.Sharkey
No problem, it happens all the time. Glad I could help!Nonce
N
18

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.

Nonce answered 28/8, 2011 at 17:28 Comment(2)
lets say the string is "@peterwateber hello" and you want to put it as "@[123:peterwateber] hello" in a hidden tag how do you do that?Al
You would probably need to use the selected item in the select event handler. Feel free to open a new question if you need a more specific answer.Nonce
H
1

I wrote a jQuery plugin based on the jQuery UI autocomplete functionality. Here is my solution:

http://www.hawkee.com/snippet/9391/

You call it like this:


$('#inputbox').triggeredAutocomplete({
    hidden: '#hidden_inputbox',
    source: "/search.php",
    trigger: "@"
});
Housetop answered 6/5, 2012 at 3:46 Comment(0)
A
0

you can use autocomplete search event to detect if the text is having @ in it. If it is not @ then just return false and autocomplete will not work.

eg : $( ".selector" ).autocomplete({ search: function(event, ui) { ... } });

Amye answered 17/8, 2011 at 12:37 Comment(7)
But I would like the autocomplete to only use letters from the text immediately following @, and only pop down starting after @. With selector, won't the text from the entire query box be used? Thanks for any tips!Sharkey
are you using remote datasource to get options.Amye
Yes. Suppose I already have the options. I am really interested in how this is achieved on the front end.Sharkey
if you have any remote file to act as a datasource then you can implement your logic to consider only the text after @ in that file. and using the logic that i had mentioned above you can make sure that autocomplete is running only after @ is in the stringAmye
Sorry, I was unclear. Suppose I have all of the autocomplete options in a remote file. I want to initialize an autocomplete list after somebody types @ at somepoint within a form field, and only use the next few words after @.Sharkey
what you need has to be accomplished in two steps 1. restrict autocomplete to run untill @ is typed. this can be done by using the search event. return true from this function only after you had got @ in your string 2. when your remote file is called it will still get the complete string (including text before @) . so use some logic to return only those option that matches the string after @ let me know in which step you have doubt.Amye
@ChristopherDuBois let us continue this discussion in chatAmye
F
0

I wrote a bootstrap plugin for this. It works no matter where the @ occurs in the form field. It's for ContentEditable divs rather than text area: http://sandglaz.github.com/bootstrap-tagautocomplete/

Fortress answered 26/3, 2013 at 16:25 Comment(0)
A
0

To expatiate Andrew Whittaker's answer a bit, the source option of jQuery UI Autocomplete is used to specify an array containing the items that are to be displayed in the drop-down list once the widget is triggered. It can be defined as such an array, a function that returns such an array, or a URL to a resource which produces such an array.

If source is defined as an function, the parameters of the function, request and response, can be used to help compose its return array and supply it to the widget, respectively. request in particular is of interest to you, since its member, term contains the value of the input element to which the widget is affixed, at the time the function is invoked.

See where I'm going with this? Its pretty simple, parse request.term for the text between the @ symbol of interest and the cursor, and use that text to create the array to supply to the widget. You'll need to do a little work (or employ some ready-made functions) to be able to locate the cursor reliably in a cross-browser compatible way, however.

Check out Mentionator if you're looking for an existing plug-in that provides the functionality you're trying to emulate. It is well structured, easy to follow, and copiously commented, so you should have little trouble understanding how to take the approach I've described. It is also maintained by yours truly:) .

Assibilate answered 3/7, 2016 at 19:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.