选择jQuery UI自动完成后清除表单字段 [英] Clear form field after select for jQuery UI Autocomplete

查看:95
本文介绍了选择jQuery UI自动完成后清除表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个表单,并使用jQuery UI Autocomplete.当用户选择一个选项时,我希望该选择弹出到附加到父<p>标记的跨度中.然后,我希望清除该字段,而不是使用选择填充该字段.

I'm developing a form, and using jQuery UI Autocomplete. When the user selects an option, I want the selection to pop into a span appended to the parent <p> tag. Then I want the field to clear rather than be populated with the selection.

我显示的跨度很好,但是我无法清除该字段.

I have the span appearing just fine, but I can't get the field to clear.

如何取消jQuery UI Autocomplete的默认选择操作?

How do you cancel jQuery UI Autocomplete's default select action?

这是我的代码:

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>");
    }
});

仅执行$(this).val("");不起作用.令人发疯的是,如果我忽略自动完成功能,并且几乎在用户键入逗号时采取措施,那么几乎所有的功能都可以正常工作:

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.

推荐答案

添加$(this).val(''); return false;select函数的末尾以清除该字段并取消该事件:)

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

这将防止更新值.您可以在109行附近周围看到.

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 UI自动完成后清除表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆