开发者

jQuery UI Autocomplete: Enter to complete

Using jQuery autocomplete, is it 开发者_Python百科possible to make it so that the first item is automatically highlighted and will be filled in when the user hits enter, but not when they tab out of the input (input loses focus)?

The closest I've found is this, but that autocompletes on lose-focus.


I think I have a solution that works - without breaking the existing behaviour - by extending $.ui.autocomplete and overriding the _suggest method.

$.widget('ui.myAutocomplete', $.extend({}, $.ui.autocomplete.prototype, {
    _suggest : function(items) {
        // Call ui.autocomplete's parent method
        $.ui.autocomplete.prototype._suggest.call(this, items);

        // Find the first list item
        var item = this.menu.element.children()[0];

        // Make this item active.
        // An event is expected so a fake one is passed as a parameter.
        this.menu.activate(new jQuery.Event('null.event'), $(item));
    }
}));

You can now use the new sub-class $.ui.myAutocomplete in the same way as $.ui.autocomplete

$(function() {
    var source = [
        'test 1'
        ,'test 2'
        ,'test 3'
    ];

    $('#selector')
        .myAutocomplete({
            source : source
        });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜