我正在开发一个表单,并使用jQuery UI自动完成.当用户 Select 一个选项时,我希望该选项弹出到附加到parent <p>标记的范围中.然后,我希望字段被清除,而不是被 Select 填充.

我的跨度看起来很好,但我无法让场地清理干净.

如何取消jQuery UI自动完成的默认 Select 操作?

这是我的代码:

var availableTags = ["cheese", "milk", "dairy", "meat", "vegetables", "fruit", "grains"];
$("[id^=item-tag-]").autocomplete({
    source: availableTags,

    select: function(){
        var newTag = $(this).val();
        $(this).val("");
        $(this).parent().append("<span>" + newTag + "<a href=\"#\">[x]</a> </span>");
    }
});

Simply doing $(this).val(""); doesn't work. What is maddening is that almost the exact function works fine if I ignore autocomplete, and just take action when the user types a comma as such:

$('[id^=item-tag-]').keyup(function(e) {
    if(e.keyCode == 188) {
        var newTag = $(this).val().slice(0,-1);
        $(this).val('');
        $(this).parent().append("<span>" + newTag + "<a href=\"#\">[x]</a> </span>");
    }
});

The real end result is to get autocomplete to work with multiple selections. If anybody has any suggestions for that, they would be welcome.

推荐答案

Add $(this).val(''); return false; to the end of your select function to clear the field and cancel the event :)

This will prevent the value from being updated. You can see how it works around line 109 here.

The code in there checks for false specifically:

if ( false !== self._trigger( "select", event, { item: item } ) ) {
  self.element.val( item.value );
}

Jquery相关问答推荐

在 JQuery DataTable 中通过按钮单击传递 ID

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

如何使 Bootstrap 轮播滑块使用移动左/右滑动

jQuery:获取数据属性

更改高亮 colored颜色

jquery如何判断ajax调用的响应类型

jQuery获取DOM node ?

jQuery $(document).ready () 触发两次

jQuery从下拉列表中删除一个选项,给定选项的文本/值

数据表警告(表 id = 'example'):无法重新初始化数据表

jQuery增量读取AJAX流?

如何更改 dropzone.js 中的默认文本?

从父 node 中删除所有子 node ?

如何检测 window.print() 完成

覆盖 twitter bootstrap Textbox Glow and Shadows

如何使 jQuery Contains 不区分大小写,包括 jQuery 1.8+?

如何使用 javascript (jquery) 将整数值添加到返回字符串的值中?

AngularJS:使用 jQuery 更改时,ng-model 绑定不更新

如何在 DOM 中移动 iFrame 而不会丢失其状态?

自调用函数前的分号?