Modify jQuery autocomplete not to submit eagerly on Enter

后端 未结 4 954
悲哀的现实
悲哀的现实 2021-01-14 22:55

Our users complain that when they press the enter key after pasting or typing values in a jQuery autocomplete widget the form is submitted.

It\'s extremely annoyin

4条回答
  •  借酒劲吻你
    2021-01-14 23:49

    This question is similar to this one. While the solutions on that page are straight forward, they depend on the ID's of elements on the page. I use autocomplete on lots of pages so I prefer gdoron's approach (on this page). Thanks to him for doing the heavy lifting.

    However, I think there is a bug in his code. If you go to an autocomplete field that already has content and type a return, it will submit the form. Here is a fix (the change is the second "if block in cancelAutocompleteSumbission):

    function cancelAutocompleteSumbission(e) {
    // Make sure this is a nodeElement and the button pressed was Enter-Return
    if (!this.nodeType || e.which != 13)
        return;
    
    if (!$(this).autocomplete('widget').is(':visible') && e.which === 13){
        return false;
    }
    
    // If the widget is visible we simply want to close the widget.
    if ($(this).autocomplete('widget').is(':visible')) {
        $(this).autocomplete('close');
        return false;
        }
    }
    
    // Making a private scope to avoid naming collision.
    $.fn.autocomplete = (function () {
        // Cache the old autocomplete function.
        var oldAutocomplete = $.fn.autocomplete;
    
        // This will be the new autocomplete function.
        return function () {
            // If the first argument isn't "destroy" which
            // should restore the input to it's initial state.
            if (!/^destroy$/i.test(arguments[0]))
                // Attach event to the input which will prevent Enter submission as
                // explained above.
                this.keypress(cancelAutocompleteSumbission);
            // We need to restore the input to it's initial state,
            // detach the keypress callback.
            else
                this.off('keypress', cancelAutocompleteSumbission);
    
            // Call the cached function with the give "this" scope and paramteres.
            return oldAutocomplete.apply(this, arguments);
        };
    })();
    

    Live Demo

提交回复
热议问题