mikesir87
mikesir87

Reputation: 1797

jQuery Autocomplete Plugin that triggers after token

I'm building an application, and would like to do an autocomplete within a textarea, much like how Twitter/Facebook does theirs with the @[name]. However, I would like to it trigger when I enter [TID:x], where x is an integer of any length.

It appears that Twitter/Facebook start their autocomplete after you hit the @ sign, and then sends the text data after it for the autocomplete. Does anyone have any idea if the jQuery UI plugin (or any other plugin) can do something like this?

Upvotes: 5

Views: 3603

Answers (2)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

This is indeed possible. You can tap into the autocomplete widget's events (search and select) to accomplish 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 make it autocomplete in the middle of the string.
  • To complete this example, you'd need to do some work with figuring out the position of the cursor in the input field and inserting the text there instead
  • Probably other bugs, but I definitely think it's doable. Hope this gets you started.

Upvotes: 5

daniel.mattes
daniel.mattes

Reputation: 51

I have created a plugin for that, which uses jQuery-UI Autocomplete and Andrew's example (thanks for that).

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

Demo: 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"
  ]
});

Best, Daniel

Upvotes: 5

Related Questions