jQuery自动完成输入框回车键问题

9
我有一个使用jQuery自动完成的搜索文本框。当我在文本框中输入内容时,它会显示一些建议,但没有选择任何一个。
我发现现在不支持selectFirst: true。如果我在下拉列表中选择了一个项目并按下回车键,则可以正常工作。
问题是,如果用户输入app来寻找苹果并按下回车键,它会尝试提交带有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>

请注意,这里使用的是<input type='button'而不是'submit',所以默认的回车提交表单的功能不会生效。我猜是自动填充功能正在提交表单。

如果您期望 selectFirst 选项能够正常工作,那么默认情况下第一个选项是否被聚焦会怎样? - j809
是的,那样最好,但 selectFirst 没有起作用。 - Ashutosh
3个回答

16
如果您正在使用此网址: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;
      }
    }
 });

3
如果您正在使用jQuery UI实现自动完成功能,您只需要指定autoFocus: true选项即可。
它会自动选择第一个结果,当按下回车键时,它将使用第一个结果。
$( ".selector" ).autocomplete({
  autoFocus: true,
  source: function (request, response) {
    //your code
  },
  select: function(event, ui) {
    //your code
  }
});

1
我遇到了类似的问题,这是我解决它的方法。
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;
}
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接