Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 380
mikesir87 Avatar asked Dec 30 '10 16:12

mikesir87


2 Answers

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.
like image 112
Andrew Whitaker Avatar answered Nov 05 '22 06:11

Andrew Whitaker


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

like image 38
daniel.mattes Avatar answered Nov 05 '22 06:11

daniel.mattes