【问题标题】:Add autoFill capabilities to jQuery-UI 1.8.1为 jQuery-UI 1.8.1 添加自动填充功能
【发布时间】:2011-02-25 09:32:24
【问题描述】:

这是我目前拥有的,不幸的是我似乎无法弄清楚如何让autoFill 与 jQuery-UI 一起使用...它曾经与直接的 Autocomplete.js 一起使用

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" type="text/javascript"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.1.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script>

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


    var thesource = "RegionsAutoComplete.axd?PID=3"
    $(function () {
        function log(message) {
            $("<div/>").text(message).prependTo("#log");
            $("#log").attr("scrollTop", 0);
        }

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

        $("#regions").autocomplete({
            source: thesource,
            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('');
                }
                else {
                    //THIS IS CURRENTLY NOT "LOGGING" THE "UI" DATA
                    //IF THE USER DOES NOT EXPLICITLY SELECT
                    //THE SUGGESTED TEXT
                    //PLEASE HELP!!!
                    log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
                }
            }
        }).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());
            }
        });
    });


</script>

我在后端的 JSON 是这样的

[
    { "label": "Canada", "value": "Canada", "id": "1" },
    { "label": "United States", "value": "United States", "id": "2" },
]

我已使用答案 here 来使 mustMatch 正常工作,但不幸的是,如果我从输入框“tab”离开,或者我完全键入单词而不是实际选择建议的文本,我会得到“Nothing” selected" 响应而不是值和 ID。

有谁知道当您没有实际选择字段时如何从自动完成中提取 id?


基本上,我正在寻找的是类似于在此处找到的 Month (local): 示例:http://jquery.bassistance.de/autocomplete/demo/

但显然使用 jQuery-UI 而不是 jquery.autocomplete.js

【问题讨论】:

  • 恕我直言来自 bassistance.de 的人做得很好,你为什么要重新发明井!?如果你使用 jQuery UI 但取消选择 Autocomple 组件并使用来自 bassistance.de 的组件,你会做得更好 - jQuery UI Autocomplete 7.45 KB minified - jQuery plugin: Autocomplete 13.7 KB 缩小
  • 这是一个很好的观点,但来自 bassistance.de 的那个不在我能找到的任何 CDN 中。他们说 dev.jquery.com 上的那个将被取消以支持 jQuery-UI
  • 旁注:尽量避免在 JavaScript 对象和数组中出现尾随逗号。有些浏览器不能正确处理它们。
  • 我更新了 jQuery-UI 组合框演示以支持自动填充。在此评论中查看我的答案:stackoverflow.com/questions/2587378/…

标签: jquery json jquery-ui jquery-validate autofill


【解决方案1】:

自动填充的 JQuery UI 版本中已弃用 AutoFill,不再支持 jquery.autocomplete 插件。

Here is a link to a github solutiuon. 如果您跳出该字段,这将自动选择列表中的第一项,并将“selectFirst: true”设置为您的自动完成调用的选项。

(function( $ ) {

$( ".ui-autocomplete-input" ).live( "autocompleteopen", function() {
    var autocomplete = $( this ).data( "autocomplete" ),
        menu = autocomplete.menu;

    if ( !autocomplete.options.selectFirst ) {
        return;
    }

    menu.activate( $.Event({ type: "mouseenter" }), menu.element.children().first() );
});

}( jQuery ));

【讨论】:

  • 调用此扩展的最佳方式是什么?我修改了代码,使其在准备好的文档上运行,并且它可以工作,但我认为我遗漏了一些东西 - 有没有更简单的方法? (我对 jquery/js 还是很陌生)
  • 这不是很明显,我同意,但基本上发生的情况是当您调用 autoComplete 方法时,JQuery 会在文本框中添加一个名为“.ui-autocomplete-input”的 css 类。此函数自动附加到该类并监视其事件以选择项目。除了在自动完成初始化后将代码添加到标题之外,您实际上不需要做任何事情。
  • 请注意,它会检查是否设置了 autocomplete.options.selectFirst,否则只会返回。您需要将 selectFirst: true, 添加到配置对象,或删除 if 块
【解决方案2】:

如果您只是想自动填充,这是我正在使用的代码。

$("#regions").autocomplete({
        source: thesource
    }).live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        //if TAB or RETURN is pressed set the value of the textbox to the text of the first suggestion
        if ((keyCode == 9 || keyCode == 13) && $(".ui-autocomplete").is(":visible")) {
            $(this).val($(".ui-autocomplete li:visible:first").text());
        }
    });

【讨论】:

    【解决方案3】:

    演示: http://jsbin.com/akile3

    更新 2: 支持 TAB! ;)

    演示: http://jsbin.com/akile3/8

    试试这样的:

    不确定是不是你想要的,反正如果匹配的话它会自动填充整个单词!

    $(function() {
     var json_source = [
            { "label": "Canada", "value": "Canada", "id": "1" },
            { "label": "United States", "value": "United States", "id": "2" }];
    
        $('<span id="hold"></span>').insertAfter('#regions');
        var $text_was = $('#hold');
        var $log = $('#log');
    
        $("#regions").autocomplete({
            minLength: 3,
            source: json_source,
            open: function(event, ui) {
                var first_option = $('.ui-autocomplete li:eq(0) a').text();
                $(this).text(first_option);
                $text_was.text(first_option);
            },
            change: function(event, ui) {
              var prev_text = $text_was.text() ? $text_was.text() : json_source[0].value ;
                $log.empty();
                var message = (prev_text != this.value) ? 
                'Nothing selected, input was ' + prev_text : 
                'Selected: ' + ui.item.value + ' aka ' + ui.item.id;
                if (prev_text != this.value) 
                  $(this).val( prev_text  );
    
                $log.append(message);
            },
            select: function(event, ui) {
                $text_was.text(ui.item.value);
                $(this).blur();
            }
        }).blur(function(){
          if( this.value == '' )
         $(this).autocomplete('search', json_source[0].value );
        return false;
      });
    });​
    

    【讨论】:

    • 谢谢你。我在 jsbin 上尝试过,但问题是当我使用“TAB”导航离开该字段时,我没有从 AutoSuggest 获得适当的数据。我需要它为我自动填充。
    • 我意识到这是可行的,但是上面的代码没有得到 ID,除非它被实际点击。即:aka: #
    • @rockinthesixstring - 不完全是,假设您在 Autocomplete 插件之外提取 json 数组,然后,您可以使用 ex. 访问 id:json_source[0].id 看看这个另一个示例 jsbin.com/akile3/10 注意: 该示例旨在提醒您是否将所有字段留空并使用 TAB。
    猜你喜欢
    • 2012-02-02
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多