如何在jQuery UI自动完成中实现“mustMatch”和“selectFirst”?

38

我最近把我的一些自动完成插件从bassistance生产的转移到了jQuery UI自动完成

如何使用回调和其他选项实现“mustMatch”和“selectFirst”,而不修改核心自动完成代码本身?

13个回答

40

我认为我解决了这两个特性...

为了使事情变得更容易,我使用了一个常见的自定义选择器:

$.expr[':'].textEquals = function (a, i, m) {
    return $(a).text().match("^" + m[3] + "$");
};

代码的其余部分:

$(function () {
    $("#tags").autocomplete({
        source: '/get_my_data/',
        change: function (event, ui) {
            //if the value of the textbox does not match a suggestion, clear its value
            if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                $(this).val('');
            }
        }
    }).live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        //if TAB or RETURN is pressed and the text in the textbox does not match a suggestion, set the value of the textbox to the text of the first suggestion
        if((keyCode == 9 || keyCode == 13) && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)) {
            $(this).val($(".ui-autocomplete li:visible:first").text());
        }
    });
});
如果你的自动完成建议中包含正则表达式使用的任何“特殊”字符,那么你必须在自定义选择器中对m[3]中的这些字符进行转义:
function escape_regexp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

并更改自定义选择器:

$.expr[':'].textEquals = function (a, i, m) {
  return $(a).text().match("^" + escape_regexp(m[3]) + "$");
};

1
我该如何自定义此插件以使用在焦点、选择等事件参数旁边传递的ui对象? - Gazillion
我已经接近成功了(只有必须匹配的部分),但它似乎会清除值,无论是建议的还是不建议的。 有什么想法? :/ - John Hunt
更新2:看起来正则表达式即使在事情相同的情况下也会返回null,所以可能存在问题。我想这可能是因为我的字符串实际上有方括号,这可能会破坏正则表达式。 - John Hunt
更新3:是正则表达式字符搞乱了它——已经编辑了答案,以防其他人遇到这个问题。 - John Hunt
如果您的自动完成具有多个值,则此解决方案无效。有什么建议吗? - leora
显示剩余4条评论

36

我使用了这么简单的代码作为mustMatch,它运行良好。希望对别人有所帮助。

        change: function (event, ui) {
            if (!ui.item) {
                 $(this).val('');
             }
        }

太好了,谢谢!你实现了自动填充吗?我也在寻找这个功能 :) - Jonathan Clark
2
请注意,您应确保 autoFocus: true - Elliott
这就是我一直在寻找的。 - Ravi Khambhati

3

我认为我用这段代码实现了mustMatch功能...不过需要进行彻底的测试:

<script type="text/javascript">
    $(function() {
        $("#my_input_id").autocomplete({
            source: '/get_my_data/',
            minChars: 3,
            change: function(event, ui) {
                // provide must match checking if what is in the input
                // is in the list of results. HACK!
                var source = $(this).val();
                var found = $('.ui-autocomplete li').text().search(source);
                console.debug('found:' + found);
                if(found < 0) {
                    $(this).val('');
                }
            }
        });
    });
</script>

好的,但我可以提交一个空值。我认为你需要实现一个keydown函数。 - CyberJunkie

2
我发现这个问题很有用。
我想我会发布我现在正在使用的代码(改编自Esteban Feldman的答案)。
我添加了自己的mustMatch选项和一个CSS类来突出显示问题,然后重置文本框的值。
       change: function (event, ui) {
          if (options.mustMatch) {
            var found = $('.ui-autocomplete li').text().search($(this).val());

            if (found < 0) {
              $(this).addClass('ui-autocomplete-nomatch').val('');
              $(this).delay(1500).removeClass('ui-autocomplete-nomatch', 500);
            }
          }
        }

CSS(层叠样式表)
.ui-autocomplete-nomatch { background: white url('../Images/AutocompleteError.gif') right center no-repeat; }

@GordonB - 你有autocompleteerror.gif这张图片吗? - leora

1
我发现了一个问题。当建议列表处于活动状态时,即使值与建议不匹配,您也可以提交表单。为了防止这种情况,我添加了以下内容:
$('form').submit(function() {
        if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
            $(this).val('');
            $("span").text("Select a valid city").show();
            return false;
        }
});

这将防止表单被提交并显示一条消息。


注意:这似乎是对 Doc Hoffiday 接受的答案的评论。 - Bryan Larsen

1
也许这只是因为这是一个旧问题,但我发现最简单的解决方案已经在插件中了,你只需要使用适当的函数来访问它。
以下代码将处理自动完成失去焦点且具有无效值的情况:
change: function(e, ui) {
    if (!ui.item) {
        $(this).val("");
    }
}

这段代码与bassistance的原始功能类似,可以处理在自动完成时没有匹配项的情况:

response: function(e, ui) {
    if (ui.content.length == 0) {
        $(this).val("");
    }
}

这适用于静态数组源或JSON数据源。与 autoFocus: true 选项结合使用,似乎以高效的方式完成所有需要的操作。

您可能想处理的最后一种情况是,当在文本框中键入无效值并按下 ESCAPE 键时该怎么办。我的做法是使用第一个匹配结果的值。以下是我如何实现...

首先,在自动完成插件之外声明一个变量来保存最佳匹配结果。

var bestMatch = "";

然后使用以下选项:
open: function(e, ui) {
    bestMatch = "";

    var acData = $(this).data('uiAutocomplete');
    acData.menu.element.find("A").each(function () {
        var me = $(this);

        if (me.parent().index() == 0) {
            bestMatch = me.text();
        }
    });
}

最后,将以下事件添加到您的自动完成功能中:
.on("keydown", function(e) {
    if (e.keyCode == 27)        // ESCAPE key
    {
        $(this).val(bestMatch);
    }
})

当按下Escape键时,您可以轻松地强制该字段为空。您所要做的就是在按键时将值设置为空字符串,而不是bestMatch变量(如果选择清空字段,则根本不需要该变量)。

1

我用来实现“mustMatch”的解决方案:

<script type="text/javascript">
...

$('#recipient_name').autocomplete({
    source: friends,
    change: function (event, ui) {
        if ($('#message_recipient_id').attr('rel') != $(this).val()) {
            $(this).val('');
            $('#message_recipient_id').val('');
            $('#message_recipient_id').attr('rel', '');
        }
    },
    select: function(event, ui) {
        $('#message_recipient_id').val(ui.item.user_id);
        $('#message_recipient_id').attr('rel', ui.item.label);
    }
}); 

...
</script>

1
这个 JQuery-UI 官方演示有一个 mustMatch 功能,以及其他很酷的东西:http://jqueryui.com/demos/autocomplete/#combobox 我将其更新,添加了 autoFill 和其他一些功能。
Javascript:
/* 从http://jqueryui.com/demos/autocomplete/#combobox中借鉴 * * 并添加了以下选项。 * * - autoFill(默认值:true):如果存在匹配项,则选择第一个值而不是清除它 * * - clearButton (默认值:true):添加一个“清除”按钮 * * - adjustWidth(默认值:true):如果为true,将设置自动完成宽度与旧选择相同。(需要jQuery1.4.4在IE8上工作) * * - uiStyle(默认值:false):如果为真,将添加类以使自动完成输入采用jQuery-UI样式 */ (function($){ $.widget("ui.combobox", { options: { autoFill: true, clearButton: true, adjustWidth: true, uiStyle: false, selected: null }, _create: function() { var self = this, select = this.element.hide(), selected = select.children(":selected"), value = selected.val() ? selected.text() : "", found = false; var input = this.input = $("") .attr('title', '' + select.attr("title") + '') .insertAfter(select) .val(value) .autocomplete({ delay: 0, minLength: 0, source: function(request, response) { var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); var resp = select.children("option").map(function() { var text = $(this).text(); if (this.value && (!request.term || matcher.test(text))) return { label: text.replace(new RegExp("(?![^&;]+;)(?!]*)(" + $.ui.autocomplete.escapeRegex(request.term) + ")(?![^]*>)(?![^&;]+;)", "gi"), "$1"), value: text, option: this }; }); found = resp.length > 0; response(resp); }, select: function(event, ui) { ui.item.option.selected = true; self._trigger("selected", event, { item: ui.item.option }); }, change: function(event, ui) { if (!ui.item) { var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"), valid = false; select.children("option").each(function() { if ($(this).text().match(matcher)) { this.selected = valid = true; return false; } }); if (!valid || input.data("autocomplete").term == "") { // set to first suggestion, unless blank or autoFill is turned off var suggestion; if (!self.options.autoFill || input.data("autocomplete").term == "") found = false; if (found) { suggestion = jQuery(input.data("autocomplete").widget()).find("li:first")[0]; var option = select.find("option[text=" + suggestion.innerText + "]").attr('selected', true); $(this).val(suggestion.innerText); input.data("autocomplete").term = suggestion.innerText; self._trigger("selected", event, { item: option[0] }); } else { suggestion = { innerText: '' }; select.find("option:selected").removeAttr("selected"); $(this).val(''); input.data("autocomplete").term = ''; self._trigger("selected", event, { item: null }); } return found; } } } });
if (self.options.adjustWidth) { input.width(select.width()); }
if (self.options.uiStyle) { input.addClass("ui-widget ui-widget-content ui-corner-left"); }
input.data("autocomplete")._renderItem = function(ul, item) { return $("
  • ") .data("item.autocomplete", item) .append("" + item.label + "") .appendTo(ul); };
    this.button = $("") .attr("tabIndex", -1) .attr("title", "Show All Items") .insertAfter(input) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass("ui-corner-all") .addClass("ui-corner-right ui-button-icon") .click(function() { // close if already visible if (input.autocomplete("widget

    CSS(.hjq-combobox是一个包装span)

    .hjq-combobox .ui-button { margin-left: -1px; }
    .hjq-combobox .ui-button-icon-only .ui-button-text { padding: 0; }
    .hjq-combobox button.ui-button-icon-only { width: 20px; }
    .hjq-combobox .ui-autocomplete-input { margin-right: 0; }
    .hjq-combobox {white-space: nowrap;}
    

    注意:此代码正在https://github.com/tablatom/hobo/blob/master/hobo_jquery_ui/vendor/assets/javascripts/combobox.js更新和维护。


    0

    回复晚了,但希望对某人有所帮助!

    考虑自动完成小部件中的两个事件:

    1)更改 - 当字段模糊和值更改时触发。

    2)响应 - 在搜索完成并显示菜单时触发。

    按如下方式修改更改和响应事件:

    change : function(event,ui)
    {  
    if(!ui.item){
    $("selector").val("");
    }
    },
    
    response : function(event,ui){
    if(ui.content.length==0){
      $("selector").val("");
    }
    }
    

    希望这能有所帮助!

    0
    我正在以稍微不同的方式进行,如果某个术语的结果数量为零,则缓存结果并清除文本字段:
    <script type='text/javascript'>
    function init_autocomplete( args )
    {
         var resultCache = {};
         var currentRequestTerm = null;
    
         var closeCallback = function()
         {
             // Clear text field if current request has no results
             if( resultCache[currentRequestTerm].length == 0 )
                 $(args.selector).val('');
         };
    
         var sourceCallback = function( request, responseCallback )
         {
             // Save request term
             currentRequestTerm = request.term;
    
             // Check for cache hit
             // ...
             // If no cache hit, fetch remote data
             $.post(
                 dataSourceUrl,
                 { ...  }, // post data
                 function( response )
                 {
                     // Store cache
                     resultCache[request.term] = response;
    
                     responseCallback( response );
                 }
         };
    
         $(args.selector).autocomplete({
             close:  closeCallback,
             source: sourceCallback
         });
    }
    </script>
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接