问题描述
我正在使用 jquery的Ajax自动完成
,而我的HTML代码是
I'm working with Ajax autocomplete for jquery
and my HTML code is
<input type="text" name="autocomplete" id="globalBCCAutoComplete">
和我的 autocomplete
JS代码是
$(document).ready(function() {
var countries = [
{ value: '{contract_name}', data: 'Contact Name'},
{ value: '{user_company}', data: 'User Company' }
];
$('#globalBCCAutoComplete').autocomplete({
lookup: countries,
onSelect: function (suggestion) {
//alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});
,它工作正常,但是当我在文本字段中添加value属性时:
and it is working fine, but when I add value attribute in text field:
<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="This is test">
添加值后,自动完成
不起作用.有什么问题吗?
After added value autocomplete
is not working. What is the problem?
推荐答案
据我了解,您想要做的就是将输入中设置的初始值附加到建议对象,以便将其用作前缀.
from the comments I understand all you want is to append the initial value set on the input to the suggestions object so it will act as a prefix.
你为什么不这么说?
使用您的代码:
HTML:
<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="john">
JAVASCRIPT:
JAVASCRIPT:
$(document).ready(function() {
let countries = [
{ value: '{contract_name}', data: 'Contact Name'},
{ value: '{user_company}', data: 'User Company' }
];
//get current value from the textbox
let initialTextValue = $('#globalBCCAutoComplete').val().trim();
//append the value to your JSON objects.
$(countries).each(function(key, country) {
country.value = initialTextValue + ' ' + country.value
});
//the rest of your code:
$('#globalBCCAutoComplete').autocomplete({
lookup: countries,
onSelect: function (suggestion) {
console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});
jsfiddle示例: https://jsfiddle.net/7g4nnnoz/5/
jsfiddle example: https://jsfiddle.net/7g4nnnoz/5/
另一种选择是带有.map()函数的ES6箭头函数:
an alternative would be ES6 arrow function with the .map() function:
//append the values to the json object.
countries.map( (country) => {
country.value = initialTextValue + ' ' + country.value
});
这篇关于文本字段不为空时,Ajax自动完成jQuery不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!