Reputation: 263
I'm working with Ajax autocomplete for jquery
and my HTML code is
<input type="text" name="autocomplete" id="globalBCCAutoComplete">
and my autocomplete
JS code is
$(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);
}
});
});
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?
Upvotes: 0
Views: 835
Reputation: 8131
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.
why did not you say so ?
using your code:
HTML:
<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="john">
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 example: https://jsfiddle.net/7g4nnnoz/5/
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
});
Upvotes: 1