javascript jQuery UI 自动完成行为。如何在输入时搜索自由文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3785993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery UI Autocomplete behaviour. How to search free text on enter?
提问by John
first question (and hopefully, but doubtfully my only one)
第一个问题(希望是我唯一的一个)
I'm using the jQuery UI Autocomplete. Here is sample code to replicate my issue.
我正在使用 jQuery UI 自动完成。这是复制我的问题的示例代码。
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
});
When a user types 'J' they will be presented with 'Clojure' and 'JavaScript' as suggestions.
当用户键入“J”时,他们将看到“Clojure”和“JavaScript”作为建议。
I have omitted Java from this list, if the user wants to search for Java, they type 'Java', press the enter key but the form does not submit. If you add a space the 'JavaScript' suggestion disappears and the form can be submitted by pressing the enter key.
我从这个列表中省略了 Java,如果用户想搜索 Java,他们输入“Java”,按回车键但表单没有提交。如果您添加一个空格,“JavaScript”建议就会消失,并且可以通过按 Enter 键来提交表单。
I am creating a free search, I want users to be able to search by pressing enter even if there are suggestions available.
我正在创建一个免费搜索,即使有可用的建议,我也希望用户能够通过按 Enter 进行搜索。
$("#autocomplete").keypress(function(event) {
alert(event.keyCode);
if (event.keyCode=='13') $this.closest('form').submit();
});
I tried the above thinking I could manually detect a submit keypress and submit the form, but the alert shows all keys are detected EXCEPT submit which seems to be suppressed by the autocomplete.
我尝试了上述想法,我可以手动检测提交按键并提交表单,但警报显示检测到所有键,但似乎被自动完成抑制的提交除外。
Any help is greatly appreciated! Thanks.
任何帮助是极大的赞赏!谢谢。
回答by ryanulit
UPDATE
更新
I had to make a few changes, but this code works fine on my side after doing that. First, e.keycode should be e.keyCode. I didn't think the case mattered, but it does. Also, make sure you are not quoting the 13 when you check for the keyCode to be the enter button. It will not work correctly if you do so. Here's the new code:
我不得不进行一些更改,但是在这样做之后,这段代码在我这边工作正常。首先,e.keycode 应该是 e.keyCode。我不认为这个案子重要,但它确实重要。另外,请确保在检查 keyCode 是否为输入按钮时没有引用 13。如果您这样做,它将无法正常工作。这是新代码:
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
}).keypress(function(e) {
if (e.keyCode === 13) {
$(this).closest('form').trigger('submit');
}
});
The keypress function should look like below, and also, you can chain the autocomplete and keypress functions to make it easier on you. Below code should work.
按键功能应如下所示,此外,您可以链接自动完成功能和按键功能,让您更轻松。下面的代码应该可以工作。
var suggestions = ["C", "Clojure", "JavaScript", "Perl", "PHP"];
$("#autocomplete").autocomplete({
source: suggestions
}).keypress(function(e) {
if (e.keycode === 13) {
$(this).closest('form').trigger('submit');
}
});
回答by richardsun
I had a similar problem, the jquery-ui autocomplete widget fires the select event when the user selects a suggestion from the list, whether the selected suggestion was clicked or the enter key was pressed. But it did nothing if the user typed text and pressed the enter key withoutselecting an item from the list. When that happens, I need to do a search.
我有一个类似的问题,当用户从列表中选择一个建议时,jquery-ui 自动完成小部件会触发 select 事件,无论是单击选定的建议还是按下 Enter 键。但是如果用户输入文本并按下回车键而没有从列表中选择一个项目,它什么也没做。发生这种情况时,我需要进行搜索。
It was easy to add a keypressevent handler, but it fired whether a selection had been made or not. So I added a variable, didSelect, to maintain the selection state.
添加keypress事件处理程序很容易,但无论是否进行了选择,它都会触发。所以我添加了一个变量,didSelect,来保持选择状态。
Here's the complete solution:
这是完整的解决方案:
$(function() {
var didSelect = false;
$( "#search" ).autocomplete({
source: "/my_remote_search",
minLength: 2,
search: function (event, ui) {
didSelect = false;
return true;
},
select: function( event, ui ) {
if (ui.item) {
didSelect = true;
my_select_function(ui.item);
}
}
}).keypress(function(e) {
if (e.keyCode == 13) {
if ( ! didSelect ) {
my_search_function( $("#search").val() );
}
}
});
});
});
回答by Eyjólfur Gislason
Autocomplete supresses submit but this worked as a workaround for me:
自动完成抑制提交,但这对我来说是一种解决方法:
jQuery.fn.go_url = function(id) {
var url="gl10.pl?ar=2010&listi=ts&niv=stovnsnr&rl=1290693052914&stovnsnr=replaceme";
var ok;
if (ok=id.match(/^\d{6}$/)) {
url=url.replace(/replaceme/g,id);
location=url;
}
}
jQuery(function() {
jQuery( "#stovnar" ).autocomplete({
source: "autocomplete.pl?pname=stovnsnr",
minLength: 3,
select: function( event, ui ) { if (ui.item) { jQuery.fn.go_url(ui.item.id); } }
});
}).keypress(function(e) {
if (e.keyCode === 13) {
v=jQuery("#stovnar").val();
jQuery.fn.go_url(v)
}
});
回答by Peter Tizzard
Using the UI Autocomplete plugin version 1.8.5:
使用 UI Autocomplete 插件版本 1.8.5:
Look for this bit of code
寻找这段代码
"case d.ENTER:case d.NUMPAD_ENTER:a.menu.element.is(":visible")&&c.preventDefault();"
"case d.ENTER:case d.NUMPAD_ENTER:a.menu.element.is(":visible")&&c.preventDefault();"
and remove or comment it out.
并删除或注释掉它。
Essentially what was said above but from the current version of the plugin.
基本上是上面所说的,但来自插件的当前版本。
cheers
干杯
Pete
皮特
回答by gman
This is what I did
这就是我所做的
<div class="ui-widget">
<form action="javascript:alert('hey run some javascript code')">
<input id="search" />
</form>
</div>
回答by zenlord
I had the same problem, and was thinking of using validation to accomplish this, but in the end my solution looks a whole lot easier than other solutions on this page:
我遇到了同样的问题,并正在考虑使用验证来完成此操作,但最终我的解决方案看起来比此页面上的其他解决方案容易得多:
Make an input field to type the text in, named
#inputand a hidden input named#hiddeninput. Your search-backend will have to use the value for#hiddeninput.Inside your autocomplete, set the value of #hiddeninput to request.term: (I set this inside
$.ajax({ success: }))
创建一个输入字段来输入文本,命名为
#input,隐藏输入名为#hiddeninput。您的搜索后端必须使用 的值#hiddeninput。在您的自动完成中,将 #hiddeninput 的值设置为 request.term :(我在里面设置了这个
$.ajax({ success: }))
$("input#hiddeninput").val(request.term);
$("input#hiddeninput").val(request.term);
- Set the autocomplete with the select:-method to fill the hidden input with the suggestion that is chosen:
- 使用 select:-method 设置自动完成以使用选择的建议填充隐藏输入:
select: function( event, ui ) { $("input#input").val(ui.item.label), $("input#hiddeninput").val(ui.item.nr), //Auto-submit upon selection $(this).closest("form").submit(); }
select: function( event, ui ) { $("input#input").val(ui.item.label), $("input#hiddeninput").val(ui.item.nr), //Auto-submit upon selection $(this).closest("form").submit(); }
Now your search will be performed on what the user has typed until he selects something from the suggestions-list.
现在,您将根据用户输入的内容执行搜索,直到他从建议列表中选择某些内容为止。
回答by brainzone
<script>
$(function() {
$('#student').autocomplete({
source: '../ajx/student_list.php',
minLength: 3,
response: function( event, ui ) {
$('#student_id').val(ui.content[0].id);
},
select: function( event, ui ) {
$('#student_id').val(ui.item.id);
$(this).closest('form').trigger('submit');
}
}).keypress(function(e) {
if (e.keyCode === 13) {
$(this).closest('form').trigger('submit');
}
});
});
</script>
<div>
<form action='../app/student_view.php'>
<input name='student_id' id='student_id' type='hidden' value=''>
<label for='student'>Student: </label>
<input id='student' />
</form>
</div>
Here I used autocomplete to search for a student. If the user pressed ENTER, the form would submit, even if nothing was selected from the list. The 'response' event would update the value of a hidden input field with the first item in the list. They could also click or select from the list.
在这里,我使用自动完成来搜索学生。如果用户按下 ENTER,即使没有从列表中选择任何内容,表单也会提交。'response' 事件将使用列表中的第一项更新隐藏输入字段的值。他们还可以单击或从列表中选择。

