jQuery 如何在自动完成实现的文本框中设置默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17059688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set Default value in autocomplete implemented textbox?
提问by Sakthivel
I have a textbox implemented with autocomplete. Here is it.
我有一个使用自动完成功能实现的文本框。就这个。
<input id="txtcity" />
$("#txtcity").autocomplete({
source: function (request, response) {
$.ajax({
url: '@Url.Action("CityLookup", "PatientDemographic", "")', type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text, id: item.Value }
}))
}
})
},
select: function (event, ui) {
$("#CityCode").val(ui.item.id);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
This returns three results, let's say "Apple", "Banana", "Cabbage". How do I set a default value to "Banana" while rendering ? i.e, text="banana" value="2"?
这将返回三个结果,比如说“Apple”、“Banana”、“Cabbage”。渲染时如何将默认值设置为“香蕉”?即,文本=“香蕉”值=“2”?
回答by Edward
you can set the value like this after initializing Autocomplete:
您可以在初始化自动完成后设置这样的值:
$( "#txtcity" ).autocomplete({
// do whatever
}).val('Banana').data('autocomplete')._trigger('select');
Updated Example: http://jsfiddle.net/55jhx/1/
更新示例:http: //jsfiddle.net/55jhx/1/
回答by Vishwanath
Change your following line
更改您的以下行
$('#txtcity').val() = item.value;
to
到
$('#txtcity').val(item.text);
回答by user3711504
Trigger the click for the first element in the ul
to fire the select for autocomplete:
触发对中第一个元素的单击以触发ul
自动完成选择:
$("ul.ui-autocomplete li").first().trigger("click");
回答by Sushil Adhikari
I had fixed this using __response() method. Hope this help to anyone looking for the solution.
我已经使用 __response() 方法修复了这个问题。希望这对任何寻找解决方案的人都有帮助。
$( 'selector' ).autocomplete( 'instance' ).__response = function(a) {
let defaultValue = {
label : 'Not found',
value : null
}
if( a.length === 0 ) {
a.push( $instance.elements.defaultValue );
} else {
a.unshift( $instance.elements.defaultValue );
}
a && (a = this._normalize(a)), this._trigger("response", null, {
content: a
}), !this.options.disabled && a && a.length && !this.cancelSearch ? (this._suggest(a), this._trigger("open")) : this._close();
}
Thanks
谢谢
回答by pitinca
I tried:
我试过:
$( "#txtcity" ).autocomplete({
// do whatever
}).val('Banana').data('autocomplete')._trigger('select');
and it doesn't work as expected. it automatically selects the value, but this results as null
.
它没有按预期工作。它会自动选择值,但结果为null
。
So I simply tried:
所以我只是尝试:
$( "#txtcity" ).autocomplete({
// do whatever
}).val('Banana')
and this selects the value and it isn't null
.
这选择了值,它不是null
。