我在try 让自动完成功能正常工作时遇到了麻烦.

在我看来一切都没问题,但是……

<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.

推荐答案

select事件的默认行为是将input更新为ui.item.value.这段代码运行after个事件处理程序.

Simply return false or call event.preventDefault() to prevent this from occurring. I would also recommend doing something similar for the focus event to prevent ui.item.value from being placed in the input as the user hovers over choices:

$("#customer-search").autocomplete({
    /* snip */
    select: function(event, ui) {
        event.preventDefault();
        $("#customer-search").val(ui.item.label);
        $("#selected-customer").val(ui.item.label);
    },
    focus: function(event, ui) {
        event.preventDefault();
        $("#customer-search").val(ui.item.label);
    }
});

Example: http://jsfiddle.net/andrewwhitaker/LCv8L/

Jquery相关问答推荐

JQuery AJAX 成功事件未触发

第一次单击后,Ajax addEventListener 停止工作

Javascript 仅打印 iframe 内容

使用 JQuery 清除下拉列表

jQuery 中的 $this 与 $(this)

未捕获的类型错误:$.post 不是函数

具有动态大小图像的马赛克网格 gallery

如何立即启动 setInterval 循环?

javascript 正则表达式用于包含至少 8 个字符、1 个数字、1 个大写和 1 个小写的密码

如何将参数传递给 JavaScript 中的匿名函数?

jQuery:获取父母,父母ID?

为不同的 node 类型配置jstree右键上下文菜单

为什么不推荐$().ready(handler)?

是否可以在 beforeunload 弹出窗口中显示自定义消息?

用 Javascript 加载 jQuery 并使用 jQuery

jQuery 按值 Select 选项元素

从 Select 元素中获取选定的选项

5秒后jQuery自动隐藏元素

如何在文件 Select 上触发事件

在jQuery中,当它们都具有相同的名称时,如何获取单选按钮的值?