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



使用 jquery 自动完成插件时,当用户没有选择列表中的项目,而是键入有效值并按 Tab 键离开时,您会怎么做?

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

Cat
Dog
Fish 

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

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

我该如何处理这种情况?

您可能正在寻找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 ));

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

对于 jQuery 版本>= 1.8.11,请使用设置为 true 的自动对焦选项

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

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

添加 onchange 的自定义事件

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

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

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

对于 jQuery UI 1.9.2,我不得不在安德鲁·惠特克的回答中稍微改变一下斯科特·冈萨雷斯的自动选择扩展:

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

要成为

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

然后它完美地工作。

你可以这样使用

$("#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('');
    }
});

为了jQuery UI - v1.11.0,我不得不更改一点斯科特·冈萨雷斯的自动选择扩展,如下所示。

/*
 * 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 });
        }
    });
});

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

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

  1. 特鲁什凯维奇
  2. 格多伦和
  3. 加泰卡兰

编辑

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

$("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
        }
    }
})

以下代码是对 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));

另一个简单的技巧是使用 .autocomplete({ focus: and change: }) .focus将数据放入元素数据属性中,change获取它:

return $(element).autocomplete({
            source: get_db_cities,
            select: function (event, ui) {
                $(this).attr('tz',ui.item.tz);
            },
            autoFocus: true,
            focus: function (event, ui) {
                $(this).attr('tz',ui.item.tz);
                $(this).attr('label',ui.item.label); // put data in attribute
            },
            change: function () {
                $(this).val($(this).attr('label')); // take from attribute and insert as value
            }
});

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

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

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

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

/*
 * jQuery UI Autocomplete Auto Select Extension
 *
 * v 1.10
 * Jomo Frodo (jomofrodo@gmail.com)
 * 
 * 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 = '';
                        }
                    });
        });

使用 autoFocus: true

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

更新了 Scott Gonzalez 的代码以使用 Jquery-UI 1.12

(function($) {
    $.ui.autocomplete.prototype.options.autoSelect = true;
    $('body').on('blur', '.ui-autocomplete-input', 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(index, item) {
            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});
        }
    });
}(jQuery));

我已经尝试了所有这些响应,如果引入的值不在列表中,则最终的解决方案是将选择设置为空:

            $( "#input" ).autocomplete({
                source: source,
                minLength: 0,
                change: function(event, ui) {
                    if(!ui.item) {
                        $(this).val("")
                    }
                }
            }).focus(function(){            
                $(this).data("uiAutocomplete").search($(this).val());
            });

最新更新