当用户未从下拉列表中选择选项时,jQuery ui 自动完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10405932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:16:00  来源:igfitidea点击:

jQuery ui autocomplete when user does not select an option from the dropdown

jqueryjquery-uijquery-ui-autocomplete

提问by JK.

When using the jquery autocomplete plugin, what do you do when the user does not select an item in the list, but instead types a valid value and tabs away?

使用jquery 自动完成插件时,如果用户没有选择列表中的项目,而是键入有效值并跳出选项卡,您会怎么做?

eg when the auto complete list contains:

例如,当自动完成列表包含:

Cat
Dog
Fish 

And the user types cat, but does not select Catfrom the autocomplete's dropdown list and instead tabs away. Because they did not select any item from the list, the autocomplete select event does not fire, and we lose the chance to respond to it:

并且用户键入cat,但不会Cat从自动完成的下拉列表中选择,而是选择选项卡。因为他们没有从列表中选择任何项目,自动完成选择事件不会触发,我们失去了响应它的机会:

$('#Animal').autocomplete({
    source: url,
    minlength: 1,
    select: function (event, ui) {
        $("#Animal").val(ui.item.value);
        changeUsersAnimal(ui.item.id);
    }
});

How do I handle this case?

我如何处理这个案子?

采纳答案by Andrew Whitaker

You're probably looking for Scott González' autoSelectextension. Just including this extension on the page will allow the selectevent to fire if the user enters a valid value and should require no changes on your end:

您可能正在寻找Scott González 的autoSelect扩展名select如果用户输入有效值,只需在页面上包含此扩展程序即可触发事件,并且您不需要更改:

/*
 * jQuery UI Autocomplete Auto Select Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
(function( $ ) {

$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
    var autocomplete = $( this ).data( "autocomplete" );
    if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }

    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
    autocomplete.widget().children( ".ui-menu-item" ).each(function() {
        var item = $( this ).data( "item.autocomplete" );
        if ( matcher.test( item.label || item.value || item ) ) {
            autocomplete.selectedItem = item;
            return false;
        }
    });
    if ( autocomplete.selectedItem ) {
        autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
    }
});

}( jQuery ));

Here's an example using the extension: http://jsfiddle.net/vFWUt/226/

这是使用扩展名的示例http: //jsfiddle.net/vFWUt/226/

回答by Marques

With jQuery version >= 1.8.11 use the autoFocus option set to true

jQuery 版本 >= 1.8.11 使用 autoFocus 选项设置为 true

$( ".selector" ).autocomplete({ autoFocus: true });

That has the additional advantage of automatically selecting the first item in the list so the user can just press Enter or Tab to select it without having to type all the name.

这具有自动选择列表中的第一项的额外优势,因此用户只需按 Enter 或 Tab 即可选择它,而无需键入所有名称。

回答by gdoron is supporting Monica

Add a custom event of onchange

添加 onchange 的自定义事件

$('#Animal').change(function(){
    var selectedValue = this.value;
    // Do what you want here:
    ...
});

Or use the built-in changeevent of the widget:

或者使用change小部件的内置事件:

$('#Animal').autocomplete({
    source: url,
    minlength: 1,
    select: function (event, ui) {
        $("#Animal").val(ui.item.value);
        changeUsersAnimal(ui.item.id);
    }
   change: function(event, ui) { // <=======
       // ... 
       // ...
   }
});

source

来源

回答by trushkevich

For jQuery UI 1.9.2 I had to change a bit Scott González' autoSelect extension in Andrew Whitaker's answer:

对于 jQuery UI 1.9.2,我不得不在 Andrew Whitaker 的回答中稍微更改 Scott González 的 autoSelect 扩展:

var item = $( this ).data( "item.autocomplete" );

to be

成为

var item = $( this ).data( "uiAutocompleteItem" );

and then it works perfectly.

然后它完美地工作。

回答by ShriP

You can use like this

你可以这样使用

$("#inputbox").autocomplete({
    source : reuesturl,
    minLength : 1,
    select : function(event, ui) {
        $("#inputbox").attr('rel',ui.item.label);
    },
    open : function() {
        $("#inputbox").attr('rel', 0);
    },
    close : function() {                    
        if ($("#inputbox").attr('rel')=='0')
            $("#inputbox").val('');
    }
});

回答by Devraj Gadhavi

For jQuery UI - v1.11.0I had to change a bit Scott González' autoSelect extensionas below.

因为jQuery UI - v1.11.0我不得不修改一下Scott González 的 autoSelect 扩展,如下所示。

/*
 * jQuery UI Autocomplete Auto Select Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
$().ready(function () {
    $.ui.autocomplete.prototype.options.autoSelect = true;
    $(".ui-autocomplete-input").change(function (event) {
        var autocomplete = $(this).data("uiAutocomplete");

        if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }

        var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
        autocomplete.widget().children(".ui-menu-item").each(function () {
            var item = $(this).data("uiAutocompleteItem");
            if (matcher.test(item.label || item.value || item)) {
                autocomplete.selectedItem = item;
                return false;
            }
        });

        if (autocomplete.selectedItem) {
            autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
        }
    });
});

And had to apply extended autocomplete option autoSelect: truein my autocomplete definition.

并且必须autoSelect: true在我的自动完成定义中应用扩展的自动完成选项。

I took a bit of code from these answers.

我从这些答案中提取了一些代码。

  1. trushkevich
  2. gdoronand
  3. Cagatay Kalan
  1. 特鲁什凯维奇
  2. 戈多隆
  3. 卡加泰卡兰

EDIT

编辑

Here's my autocomplete definition, in case someone is interested.

这是我的自动完成定义,以防有人感兴趣。

$("your selector").autocomplete({
    // Below filter looks for the values that start with the passed in string
    source: function (request, response) {
        var matches = $.map(yourSourceArray, function (acItem) {
            if (acItem.toUpperCase().indexOf(request.term.toUpperCase()) === 0) {
                return acItem;
            }
        });
        response(matches);
    },
    // one can directly pass the source array instead like,
    // source: yourSourceArray
    autoSelect: true,
    autoFocus: true,
    minLength: 3,
    change: function (event, ui) {
        if (ui.item) {
            // do whatever you want to when the item is found
        }
        else {
            // do whatever you want to when the item is not found
        }
    }
})

回答by Kanagu

The following code is a little tweak on Scott's extension to work with jquery ui 1.10.3 version, I have tested the below code with 1.10.3 version only.

下面的代码是对 Scott 扩展的一个小调整,可以使用 jquery ui 1.10.3 版本,我只用 1.10.3 版本测试了下面的代码。

(function($) {

$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
    var autocomplete = $( this ).data( "ui-autocomplete" );
    if ( ! autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }

    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
    autocomplete.widget().children( ".ui-menu-item" ).each(function() {
        var item = $( this ).data( "ui-autocomplete-item" );
        if ( matcher.test( item.label || item.value || item ) ) {
            autocomplete.selectedItem = item;
            return false;
        }
    });
    if ( autocomplete.selectedItem ) {
        autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
    }
});
}(jQuery));

回答by jomofrodo

I was having trouble with this function in a page using jquery 1.9.1 and jquery-ui 1.10.3. Based on the Scott Gonzalez' code and the suggestions here and a few hours of thrashing, I came up with the following. Note, I wanted a solution where the user is only allowed to enter one of the values suggested by the autocomplete -- but I wanted to allow the case where the user just types in one of the allowed values without selecting it from the drop down:

我在使用 jquery 1.9.1 和 jquery-ui 1.10.3 的页面中遇到了这个功能的问题。基于 Scott Gonzalez 的代码和这里的建议以及几个小时的颠簸,我想出了以下内容。请注意,我想要一个解决方案,其中用户只允许输入自动完成建议的值之一——但我想允许用户只输入一个允许的值而不从下拉列表中选择它的情况:

/*
 * jQuery UI Autocomplete Auto Select Extension
 *
 * v 1.10
 * Jomo Frodo ([email protected])
 * 
 * This version requires an autoSelect parameter to be set on the autocomplete widget
 * 
 * e.g.,
 *      $("#autoCompleteID").autocomplete({
            source:url,
            minLength:1,
            autoSelect: true
        });
 * 
 * Based on an extension by Scott Gonz??lez (http://scottgonzalez.com) 
 * http://blog.jqueryui.com/2010/08/extensible-autocomplete/
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */

$(window).load(
        function() {

            //$.ui.autocomplete.prototype.options.autoSelect = true; 
            // Doesn't appear to work in ui 1.10.3
            // Must set the 'autoSelect' param on the autocomplete widget to get this to work.

            $(".ui-autocomplete-input").bind('autocompleteresponse',
                    function(event, ui) {
                        $(this).data('menuItems', ui.content);
                    });

            $(".ui-autocomplete-input").on(
                    "blur",
                    null,
                    function(event) {
                        var autocomplete = $(this).data("uiAutocomplete");
                        if (!autocomplete.options.autoSelect
                                || autocomplete.selectedItem) {
                            return;
                        }

                        var matcher = new RegExp("^"
                                + $.ui.autocomplete.escapeRegex($(this).val())
                                + "$", "i");
                        var menuItems = $(this).data('menuItems');
                        for (idx in menuItems) {
                            var item = menuItems[idx];
                            if (matcher.test(item.value)) {
                                autocomplete.selectedItem = item;
                                break;
                                // return false;
                            }
                        }
                        if (autocomplete.selectedItem) {
                            autocomplete._trigger("select", event, {
                                item : autocomplete.selectedItem
                            });
                        } else {
                            this.value = '';
                        }
                    });

        });

回答by Clutch

This code only autoselects once. All others after that do nothing. Any ideas?

此代码仅自动选择一次。之后的所有其他人什么都不做。有任何想法吗?

Edit: I commented out this line and it now works. Don't know why.

编辑:我注释掉了这一行,现在可以使用了。不知道为什么。

if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }

回答by Vijay Waghmare

use autoFocus: true

autoFocus: true

$('#Animal').autocomplete({
    source: url,
    **autoFocus: true,**
    minlength: 1,
    select: function (event, ui) {
        $("#Animal").val(ui.item.value);
        changeUsersAnimal(ui.item.id);
    }
});