How to prevent jQueryUI Autocomplete's default keyboard interactions?

放肆的年华 提交于 2019-12-11 14:06:36

问题


I'd specifically like to prevent the interaction when I push ENTER to prevent jQueryUI Autocomplete from selecting the currently focused item and closing the menu.

I'm referring to the following documentation: http://api.jqueryui.com/autocomplete/#event-change


回答1:


UPDATE:

The principle is the same. Just change the setTimeout function to submit your form instead (as demonstrated here: http://jsfiddle.net/X8Ghc/8/)

UPDATE:

You are correct, $(this) was supposed to refer to the ui-menu (and obviously didn't). The new fiddle, http://jsfiddle.net/X8Ghc/7/, works reasonably well.

$(document).ready(function() {
    $("#autocomplete").autocomplete({
        "open": function(e, ui) {
            //using the 'open' event to capture the originally typed text
            var self = $(this),
                val = self.val();
            //saving original search term in 'data'.
            self.data('searchTerm', val);
        },
        "select": function(e, ui) {
            var self = $(this),
                keyPressed = e.keyCode,
                keyWasEnter = e.keyCode === 13,
                useSelection = true,
                val = self.data('searchTerm');
            if (keyPressed) {
                if (keyWasEnter) {
                    useSelection = false;
                    e.preventDefault();
                    window.setTimeout(function() {
                        //since there is apparently no way to prevent this
                        //contemptible menu from closing, re-open the menu
                        //using the original search term after this handler
                        //finishes executing (using 'setTimeout' with a delay
                        //of 0 milliseconds).
                        self.val(val);
                        self.autocomplete('search', val);
                    }, 0);
                }
            }
            return useSelection;
        },
        "source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    });
});​

Original:

This works in a fiddle:

$(document).ready(function() {
    $("#autocomplete").autocomplete({
        "select": function(e, ui) {
            var keyPressed = e.keyCode,
                keyWasEnter = e.keyCode === 13,
                useSelection = true;
            console.log(e);
            if (keyPressed) {
                if (keyWasEnter) {
                    useSelection = false;
                    $(this).open(e, ui);
                }
            }
            return useSelection;
        },
        "source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
    });
});​


来源:https://stackoverflow.com/questions/13096571/how-to-prevent-jqueryui-autocompletes-default-keyboard-interactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!