【问题标题】:How to use search button with jquery ui autocomplete?如何使用带有 jquery ui 自动完成功能的搜索按钮?
【发布时间】:2019-09-21 17:19:42
【问题描述】:

我正在开发一个网站,我正在使用 jquery ui 自动完成插件使用搜索栏。

但现在只能在从下拉列表中选择后使用键盘 Enter 和鼠标单击。我也放了一个搜索按钮,但是当点击按钮时下拉菜单关闭并且没有重定向或任何事情发生。

jquery:

$(function() {
    $( "#searchbox" ).autocomplete({
        source: url + 'Home/searchallresults_shop',
        autoFocus:true,
        select: function( event, ui ) {
            $( "#searchallresults_shop" ).val( ui.item.name );
            console.log(ui);
            window.location.href = ui.item.url;
        }
    });
});

HTML:

<input type="text"  name="searchbox" id="searchbox">
<button type="submit" id="searchbutton_jq">Search</button>

如何让搜索按钮选择第一个自动完成项并重定向?

谢谢。

【问题讨论】:

  • 您的自动完成功能未绑定到您提供的任何 HTML 元素。没有 ID 为 searchbox_shop 的元素
  • @Krishna Prashatt 对不起,我的错。现在问题已编辑

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


【解决方案1】:

不清楚你在说什么。我认为您的意思是,当结果项具有焦点时,您希望它填充一个字段,以便用户可以单击“搜索”按钮,而不是按 Enter 或单击结果。我只是不确定这会多久起作用。

考虑以下代码:

var myData = [{
    value: "jquery",
    label: "jQuery",
    url: "https://jquery.com/"
  },
  {
    value: "jquery-ui",
    label: "jQuery UI",
    url: "https://jqueryui.com/"
  },
  {
    value: "sizzlejs",
    label: "Sizzle JS",
    url: "https://sizzlejs.com/"
  }
];
$(function() {
  function redirect(u) {
    window.location.href = u;
  }
  $("#searchbox").autocomplete({
    source: myData,
    autoFocus: true,
    select: function(e, ui) {
      $("#searchallresults_shop").val(ui.item.label);
      $("#searchbutton_jq").data("url", ui.item.url);
      return false;
    },
    focus: function(e, ui) {
      $("#searchallresults_shop").val(ui.item.label);
      $("#searchbutton_jq").data("url", ui.item.url);
      return false;
    }
  });
  $("#searchbutton_jq").click(function() {
    if ($(this).data("url") != undefined) {
      redirect($(this).data("url"));
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" name="searchbox" id="searchbox" />
<button type="submit" id="searchbutton_jq"> Search
  </button>
<br /> Shop: <input type="text" id="searchallresults_shop" />

如果其中一项有focus,我们可以使用回调来执行一些操作。如果持续关注并且用户单击“搜索”,则会发生预期的重定向。如果他们选择一个项目,也是如此。请记住blur 也可能触发select。点击按钮会触发blur事件,所以不清楚哪个真正冒泡到顶部,因为它们都做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2021-03-31
    • 2020-12-05
    • 2020-10-06
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多