jQuery UI自动完成 - 访问KEYDOWN / KEYUP后输入的搜索词

时间:2014-04-28 08:35:25

标签: javascript jquery jquery-ui jquery-ui-autocomplete

我如何访问用户输入的搜索字词?

我看过http://api.jqueryui.com/autocomplete/https://github.com/jquery/jquery-ui/blob/master/ui/autocomplete.js,但是没有得到它......

例如,用户在“sna”中输入,并获得一个包含自动填充候选项的菜单:

  • 抢夺
  • 喀嚓鱼

用户按下KEYDOWN,自动完成输入字段立即填充“snake”。

此时,我想获取输入字段的前一个原始值“sna”。

我怎么能做到这一点? (以编程方式,无需按ESC键)。

1 个答案:

答案 0 :(得分:1)

您可以使用$.ui.autocomplete.escapeRegex(req.term);

var wordlist= [ "about", "above", "across", "after", "against",
                "along", "among", "around", "at", "before", 
                "behind", "below", "beneath", "beside", "between"] ; 

$("#input1").autocomplete({
    // The source option can be an array of terms.  In this case, if
    // the typed characters appear in any position in a term, then the
    // term is included in the autocomplete list.
    // The source option can also be a function that performs the search,
    // and calls a response function with the matched entries.
    source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        alert(re); //THIS IS WHAT YOU WANT
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( wordlist, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});

Fiddle