【问题标题】:jQuery autocomplete enter key issuejQuery自动完成输入键问题
【发布时间】:2014-08-31 06:29:27
【问题描述】:

我有一个使用 jQuery 自动完成进行搜索的文本框。当我在文本框中输入内容时,它会显示未选择的建议。

我发现现在不支持 selectFirst: true。如果我在下拉列表中选择一个项目并按回车,它工作正常。

问题是如果用户输入 app for apple 并按下回车键,它会尝试使用 app 提交表单。表单只能使用下拉列表中的值之一提交。

我尝试禁用按 Enter 时提交的表单,以便我可以从 JavaScript 提交表单,但找不到解决方案。

这是我的代码:

$("#searchtext").autocomplete({
    source: path + 'autocompletesearch?category=' + $("select[name='category'] option:selected").val(), 
    width: '500px', 
    matchContains: true, 
    select: function(event, ui){
        $(".searchform").attr("action", path + "fullproductinfo/" + ui.item.id);
        $("input[name='searchid']").val(ui.item.value);
        $(".searchform").submit();
    }
});

还有我的表格:

        <form method="post" action="search" class="searchform">
            <div class="searchdiv">
                <input type="text" id="searchtext" name="searchtext"
                    placeholder="Search a product or a brand" autocomplete="off"/>
            </div>
            <div class="searchbutton">
                <input type="button" name="btnsearchproduct" value="Search" />
            </div>
            <div class="clear"></div>
        </form>

请注意,这里有&lt;input type='button' 而不是“提交”,因此默认输入不应适用于表单。我猜是在提交时提交表单的自动完成功能。

【问题讨论】:

  • 如果您希望selectFirst 选项起作用,您可以让第一个选项默认聚焦吗?
  • 是的,这样最好,但是 selectFirst 不起作用

标签: jquery autocomplete


【解决方案1】:

如果你使用这个:http://jqueryui.com/autocomplete/

那么你想要第一个项目到autoFocus,你现在可以使用那个选项:

$( ".selector" ).autocomplete({ autoFocus: true });

文档中提到:http://api.jqueryui.com/autocomplete/

编辑

由于你有输入键问题,你可以这样尝试:

$(".selector").keydown(function(event){
    if(event.keyCode == 13) {
      if($(".selector").val().length==0) {
          event.preventDefault();
          return false;
      }
    }
 });

【讨论】:

    【解决方案2】:

    如果您使用 jquery ui 进行自动完成,您只需要指定 autoFocus: true 选项。

    它会自动选择第一个结果,当按下回车键时它会使用第一个结果。

    $( ".selector" ).autocomplete({
      autoFocus: true,
      source: function (request, response) {
        //your code
      },
      select: function(event, ui) {
        //your code
      }
    });
    

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题,我就是这样解决的

      if ($(".selector").val().length > 0) {
      var options = $(".selector").autocomplete("option");
      var fromAutocomplete = false;
      
      jQuery.each(options.source, function(index, device) {
      if ($(".selector").val() == options.source[index]) {
          fromAutocomplete = true;
      }
      });
      
      if (!fromAutocomplete) {
      $(".selector").val("");
          $(".selector").attr("disabled", false);
          return false;
      }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        • 2010-12-04
        • 2011-08-08
        • 2013-01-22
        • 2016-05-31
        相关资源
        最近更新 更多