选择 jQueryUI 自动完成后清除表单字段

我正在开发一个表单,并使用 jQueryUI 自动完成。当用户选择一个选项时,我希望所选内容弹出到一个附加到父 <p>标记的 span 中。然后,我希望清除该字段,而不是填充所选内容。

我的跨度看起来很好,但是我无法清除这个区域。

如何取消 jQueryUI 自动补全的默认选择操作?

这是我的代码:

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("");不起作用。令人恼火的是,如果我忽略自动补全,而只是在用户键入逗号时采取行动,那么几乎完全正确的函数就可以正常工作:

$('[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>");
}
});

真正的最终结果是获得自动完成以处理多个选择。如果有人对此有任何建议,欢迎提出。

73069 次浏览

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

return false is needed within the select callback, to empty the field. but if you want to again control the field, i.e. set the value, you have to call a new function to break out of the ui.

Perhaps you have a prompt value such as :

var promptText = "Enter a grocery item here."

Set it as the element's val. (on focus we set to '').

$("selector").val(promptText).focus(function() { $(this).val(''); }).autocomplete({
source: availableTags,
select: function(){
$(this).parent().append("<span>" + ui.item.value + "<a href=\"#\">[x]</a> </span>");
foo.resetter(); // break out //
return false;  //gives an empty input field //
}
});


foo.resetter = function() {
$("selector").val(promptText);  //returns to original val
}

Instead of return false you could also use event.preventDefault().

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

It works well for me.

After select event,I used event change.

 change:function(event){
$("#selector").val("");
return false;
}

I'm a beginner!

Try This

select: function (event, ui) {
$(this).val('');
return false;
}

I just solved it forcing to lose focus:

$('#select_id').blur();
printResult();