jQuery Autocomplete Plugin that triggers after token

后端 未结 2 621
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 01:21

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

相关标签:
2条回答
  • 2021-01-06 01:38

    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.
    0 讨论(0)
  • 2021-01-06 01:41

    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

    0 讨论(0)
提交回复
热议问题