JQuery autocomplete plugin that runs after token

I am creating an application and want to do autocomplete in a text box, just like Twitter / Facebook does with @ [name]. However, I would like it to work when I enter [TID: x], where x is an integer of any length.

It seems like Twitter / Facebook starts its autocomplete after you click the @ sign, and then send text data after that for autocomplete. Does anyone have any ideas if the jQuery UI plugin (or any other plugin) can do something like this?

+5
source share
2 answers

It is really possible. You can click on widget auto- completion events ( searchand select) to do this:

var triggered = false;
var trigger = "TDI:";

$("input").autocomplete({
    source: [...],
    search: function() {
        if (!triggered) {
            return false;
        }
    },
    select: function(event, ui) {
        var text = this.value;
        var pos = text.lastIndexOf(trigger);

        this.value = text.substring(0, pos + trigger.length) +
            ui.item.value;

        triggered = false;

        return false;
    },
    focus: function() { return false; },
    minLength: 0
}).bind("keyup", function() {
    var text = this.value;
    var len = text.length;
    var last;
    var query;
    var index;

    if (triggered) {
        index = text.lastIndexOf(trigger);
        query = text.substring(index + trigger.length);
        $(this).autocomplete("search", query);
    }
    else if (len >= trigger.length) {
        last = text.substring(len - trigger.length);
        triggered = (last === trigger);
    }
});

Demo here: http://jsfiddle.net/andrewwhitaker/kCkga/

Notes:

  • This is a very limited demo. It will not work if you try to autocomplete in the middle of the line.
  • To complete this example, you will need to work to find out the position of the cursor in the input field and insert text instead
  • There are probably other errors, but I definitely think this is doable. Hope this helps you get started.
+4
source

I created a plugin for this that uses jQuery-UI Autocomplete and an Andrew example (thanks for that).

URL: https://github.com/experteer/autocompleteTrigger

: http://jsfiddle.net/dmattes/2YRgW/1/

$('input,textarea').autocompleteTrigger({
  triggerStart : '@',
  triggerEnd: '',
  source: [
    "Asp",
    "BASIC",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ]
});

, Daniel

+5

All Articles