jQuery 自动完成:事件选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7733315/
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 Autocomplete: Event-select
提问by jQuerybeast
I am trying to submit a form when an item is selected from the menu. I set class on the search form and I am using the event select for it which is found here: http://docs.jquery.com/UI/Autocomplete#event-select
当从菜单中选择一个项目时,我试图提交一个表单。我在搜索表单上设置了类,我正在使用它的事件选择,它可以在这里找到:http: //docs.jquery.com/UI/Autocomplete#event-select
Now, when you select an item using the keyboard (UP and Down), it works. But if you select an item using the mouse, it gives you the value which is previously typed.
现在,当您使用键盘(向上和向下)选择一个项目时,它会起作用。但是如果您使用鼠标选择一个项目,它会为您提供先前键入的值。
Check this screenr: http://www.screenr.com/7T0s
检查此筛选器:http: //www.screenr.com/7T0s
This is what I use for submitting:
这是我用来提交的:
$("#searchform-input").autocomplete({
select: function (a, b) {
$(".searchform1").submit()
}
});
回答by Andrew Whitaker
This is because the select
event's default behavior is executed afteryour event handler is finished running(so that you can cancel it if you so choose).
这是因为select
事件的默认行为是在您的事件处理程序完成运行后执行的(因此您可以选择取消它)。
This means that when you click something, your form is submitted before the widget has a chance to populate the input
properly.
这意味着当您单击某些内容时,您的表单会在小部件有机会input
正确填充之前提交。
You should be able to fix this by doing what the widget normally does for you:
您应该能够通过执行小部件通常为您执行的操作来解决此问题:
$("#searchform-input").autocomplete({
select: function (a, b) {
$(this).val(b.item.value);
$(".searchform1").submit()
}
});
Now, what you may be wondering is yes, but why does it work when I use the keyboard?
现在,您可能想知道是的,但是为什么当我使用键盘时它会起作用?
This happens because the focus
event actually populates the focused item in the input
(look closely; you'll see the input
populated as you move up and down the list). When you mouseover an item, the focus
event is called, populating the input
. When you select something using the enter
key, the correct value happens to be in the input
because of the focus
event.
发生这种情况是因为该focus
事件实际上填充了input
(仔细观察;input
当您在列表中上下移动时,您会看到已填充的项)。当您将鼠标悬停在某个项目上时,将focus
调用该事件,并填充input
. 当您使用enter
键选择某些内容时,正确的值恰好input
在focus
事件中。
回答by Kaszoni Ferencz
Hehe. Quite tricky this one, but incredibly simple to solve. Just delay the function 500 milliseconds, after the select event. It works perfectly. JOB DONE!! :)
呵呵。这个问题相当棘手,但解决起来非常简单。在 select 事件之后,只需将函数延迟 500 毫秒。它完美地工作。任务完成!!:)
$("#searchform-input").autocomplete({
select: function (a, b) {
setTimeout(submit,500);
}});