This previous question from 2021 (jQuery UI autocomplete with aliases) was a solution to an old question, but I’m trying to include the aliases within the dictionary instead of using two arrays.The idea is that I can use the alias or the value for lookup and save the ID for the entry. I was trying to reverse engineer the previous array solution but to no success. The below code is the working, basic autocomplete to use the dictionary, lookup the value, and return the key. I can’t figure out how to implement the matching part.
var dict = [{key:'1', value:'United States of America', alias:'usa'},
{key:'2', value:'United Kingdom', alias:'uk'},
{key:'3', value:'South Africa', alias:'sa'}]
$( "#txtValue" ).autocomplete({
source: dict,
select: function( event, ui ) {
console.log(ui.item.key);
}
});
This is the original solution for two arrays:
var tags = ["United States of America", "United Kingdom", "South Africa"];
var alias = ["usa", "uk", "sa"];
$( "#txtValue" ).autocomplete({
source: function(request, response) {
var ids = alias.indexOf(request.term);
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(tags, function(item, i) {
if(ids == i) return true;
return matcher.test(item);
}));
},
select: function( event, ui ) {
console.log(ui.item.label);
}
});
https://jsfiddle.net/s96zeq8b/ updated with Patrick’s code
3
Answers
Not sure what your trying to do, but do you even need to use a match you can get everything from the selected array item i.e : the key, value and alias not the console log demo
EDIT: fix for the match using alias
ah ok fair enough then i believe this should be what your after, it dose the same as your old script but using the
dict
array insteadNote this assumes the key value will match the corresponding value in the alias array based on the index of an item in that array matching the the key value
I hope this helps
Hopefully this demonstrates the use of the dict