【问题标题】:JQuery UI Autocomplete - Have the menu open when user clicks in the text boxJQuery UI 自动完成 - 当用户单击文本框时打开菜单
【发布时间】:2011-12-06 14:44:52
【问题描述】:

我正在使用这个JQuery autocomplete widget

如何让它在用户点击文本框时自动打开菜单?我希望用户看到所有选项。

【问题讨论】:

    标签: javascript jquery jquery-ui autocomplete jquery-autocomplete


    【解决方案1】:

    您需要手动触发search 事件并将小部件上的minLength 选项设置为零:

    $("input").autocomplete({
        minLength: 0,
        /* other options */
    }).on("focus", function () {
        $(this).autocomplete("search", "");
    });
    

    工作示例: http://jsfiddle.net/9JmVu/

    【讨论】:

    • 我无法让它在我们使用的版本中工作,但是将“on”替换为:.focus(function(){$(this).autocomplete("search", "" )});效果很好。
    • 您可能使用的是早期版本的 jQuery。
    • 不调用search事件是否可行?
    • @soham.m17:我不这么认为。你想完成什么?
    • 实际上,整个列表都可以在创建的ul 获得,我想使用可用数据并且不想刷新它。
    【解决方案2】:

    我想我真的明白了。如果将 minLength 设置为 0,然后触发搜索“”,则会打开菜单。

          $(inputSelector).autocomplete(
                  {
                      source: this.validConstructCodes,
                      minLength: 0,
                      autoFocus: true,
                      autoSelect: true
                  });
          $(inputSelector).focus(function(event) {
            $(this).autocomplete( "search" , "" );
          });
    

    【讨论】:

      【解决方案3】:

      正如 Andrew 所说,您需要触发事件。

      但是一旦您从 ajax 请求中获得了结果,最好再次显示结果而不是再次询问服务器。 minLength 值是独立的,根据服务器请求的建议可以为 2。

      $("input").autocomplete({
          minLength: 2,
          /* your options */
      }).on("focus", function () {
          /* the element with the search results */
          var uid = $("#ui-id-"+$(this).autocomplete("instance").uuid);
      
          if(uid.html().length == 0) {
              /* same as $(this).autocomplete("search", this.value); */
              $(this).keydown();
          }
          else {
              uid.show();
          }
      });
      

      【讨论】:

        【解决方案4】:

        @amalesh 的答案略有变化,可用于 jQuery Autocomplete v1.8。 我在 uuid 中添加了 +1,因为它从 0 开始,但 id 设置为 1。

        $("input").autocomplete({
                minLength: 2,
                /* your options */
        }).on("focus", function () {
                /* the element with the search results */
                //
                let uid = $("#ui-id-" + ($(this).autocomplete("instance").uuid + 1));
                if(uid.html().length === 0) {
                    /* same as $(this).autocomplete("search", this.value); */
                    $(this).keydown();
                }
                else {
                    uid.show();
                }
            });
        

        【讨论】:

        • 这将在 UUID 的末尾添加一个 1。不知道那会完成什么
        • 没错。在自动完成源代码中,您可以看到 id 的分配方式类似于 #ui-id+(++uuid) ,其中 uuid 为 0。因此它在分配前递增一。如果你只取值,那么它会寻找 #ui-id-0 ,至少在我的情况下,它是无处可寻的。
        猜你喜欢
        • 2016-08-29
        • 1970-01-01
        • 2011-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多