【问题标题】:Stop jQuery autocomplete from focussing the input field after chosen from the dropdown从下拉列表中选择后,停止 jQuery 自动完成聚焦输入字段
【发布时间】:2011-04-24 18:10:12
【问题描述】:

我正在使用来自http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/ 的 jQuery 自动完成插件 当用户从下拉列表中选择结果时,输入字段将获得焦点。我怎样才能阻止插件这样做? 我使用这篇文章中的提示使它工作:jQuery autocomplete plugin not focusing the next clicked field 但这仅在用户使用鼠标选择结果时才有效。然后输入字段没有得到关注。但是当用户使用 ENTER 键或 TAB 键时,输入仍然是焦点。

任何人都知道我可以如何更改它,以便当用户从下拉列表中选择一个值时,输入字段不会获得焦点?

非常感谢您!

问候,金

【问题讨论】:

  • 能否针对您遇到的问题发布JS Fiddle 或JS Bin 演示页面?然后我们可以看到发生了什么并提出相关建议。
  • 这听起来很像你想要发生的事情。当用户使用 enter 或 tab 键时,您希望发生什么?
  • 你知道自动完成现在是 jQueryUI 的一部分
  • 注意 (2010-06-23): 此插件已弃用,不再开发。它的successor is part of jQuery UI 和this migration guide 解释了如何从这个插件到新插件。此页面将保持原样以供参考,但不会再更新。

标签: jquery input autocomplete focus


【解决方案1】:

从插件selectCurrent() 函数中的这一行来看:

$input.trigger("result", [selected.data, selected.value]);

...每当通过鼠标或键盘选择一个选项时,自动完成输入就会触发一个“结果”事件。

您可以绑定到同一个事件并将焦点放在表单中的下一个控件上(我假设这是您想要的,而不是仅仅从当前控件中移除焦点?):

$("input").bind("result", function () {

   // Get all controls on the form
   var controls = $(this).closest("form").find("input, textarea, select, button");

   // Find the index of the next control
   var nextIndex = controls.index(this) + 1;

   // Check if this is already the last control, so wrap around to the first one
   if (nextIndex >= controls.length) nextIndex = 0;

   // Put focus on the "next" control
   controls.eq(nextIndex).focus();

});

【讨论】:

    【解决方案2】:

    你试过jQuery UI's autocomplete plugin吗?问题解决了一半——当您按 Tab 键关闭自动完成时,输入字段失去焦点。当按下 Enter 时,它仍然是焦点,但这很容易解决:

    $('#myInput').keyup(function() {
      // when Enter is pressed
      if (event.which === 13) {
        $(this).blur();
      }
    });
    

    编辑

    jQuery normalizes event 对象,因此不需要将其作为参数传递。

    【讨论】:

      【解决方案3】:
      $( "#to" ).autocomplete({
          source: availableTags,
          select: function (event, ui) {
              $( "#to" ).val( ui.item.label );
              $('#to').blur();
              return false ;
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2021-11-12
        • 1970-01-01
        • 2021-11-05
        • 2011-01-13
        • 2020-03-31
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2019-01-31
        相关资源
        最近更新 更多