自动完成将值而不是标签应用于文本框
我在尝试让自动完成功能正常工作时遇到了麻烦。
对我来说一切看起来都不错,但是......
<script>
$(function () {
$("#customer-search").autocomplete({
source: 'Customer/GetCustomerByName',
minLength: 3,
select: function (event, ui) {
$("#customer-search").val(ui.item.label);
$("#selected-customer").val(ui.item.label);
}
});
});
</script>
<div>
<input id="customer-search" />
</div>
@Html.Hidden("selected-customer")
但是,当我从下拉列表中选择一个项目时,该值将应用于文本框而不是标签。
我做错了什么?
如果我使用 firebug 查看源代码,我可以看到我的隐藏字段正在正确更新。
Im having troubles trying to get the autocomplete to work properly.
It all looks ok to me but....
<script>
$(function () {
$("#customer-search").autocomplete({
source: 'Customer/GetCustomerByName',
minLength: 3,
select: function (event, ui) {
$("#customer-search").val(ui.item.label);
$("#selected-customer").val(ui.item.label);
}
});
});
</script>
<div>
<input id="customer-search" />
</div>
@Html.Hidden("selected-customer")
However when I select an item from the dropdown the value is been applied to the textbox instead of the label.
What have I done wrong?
If I look at the source using firebug I can see that my hidden field is being updated correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
select
事件的默认行为是使用ui.item.value
更新input
。此代码在事件处理程序之后运行。只需返回
false
或调用event.preventDefault()
即可防止这种情况发生。我还建议对focus
事件执行类似的操作,以防止当用户将鼠标悬停在input
上时将ui.item.value
放置在input
中选择:示例: http://jsfiddle.net/andrewwhitaker/LCv8L/
The default behavior of the
select
event is to update theinput
withui.item.value
. This code runs after your event handler.Simply return
false
or callevent.preventDefault()
to prevent this from occurring. I would also recommend doing something similar for thefocus
event to preventui.item.value
from being placed in theinput
as the user hovers over choices:Example: http://jsfiddle.net/andrewwhitaker/LCv8L/
只是想补充一点,而不是在 select 和 focus 回调函数中通过“id”引用输入元素可以使用 this 选择器,例如:
当您为多个元素(即按类)分配自动完成功能时,它很有用:
Just would like to add that instead of referencing input element by "id" inside select and focus callback functions you can use this selector, like:
it's useful when you assign autocomplete for multiple elements, i.e. by class:
就我而言,我需要在隐藏输入中记录另一个字段“id”。因此,我在 ajax 调用返回的数据中添加了另一个字段。
并在列表底部添加了“创建新”链接。单击“新建”时,将弹出一个模式,您可以从那里创建新项目。
我认为重点是您可以添加除“标签”和“值”之外的任何额外数据字段。
我使用引导模式,它可以如下所示:
In my case, I need to record another field 'id' in an hidden input. So I add another field in the data returned from ajax call.
And have added a 'create new' link at the bottom of the list. On click the 'create new', a modal will pop up and you can create new item from there.
I think the point is that you can add any extra data field other than just 'label' and 'value'.
I use bootstrap modal and it can be as below: