JQuery - DevBridge Autocomplete - Change offer format

I have a DevBridge Autocomplete jQuery plugin that works more or less the way I want it. See the fiddle here: https://jsfiddle.net/shalan/bcex6oaq/ . This is a simple example of Suburb and City, in which the user starts typing in his suburbs, and autocomplete shows relavnt sentences. When the user makes a choice, he automatically fills in 2 read-only text fields using the appropriate city and zip code. The data structure is as follows:

var suburbData = [
    {"value":"Eastcliffe", "data":{"city":"Westwood","code":"23145"}},    
    {"value":"Creastwich","data":{"city":"Westerlyn","code":"66365"}},    
    {"value":"South Woodbury Island","data":{"city":"Fairmoor","code":"89798"}},    
    {"value":"Faighcastle","data":{"city":"Westwood","code":"23144"}},
    {"value":"Brightkeep","data":{"city":"Merrowshore","code":"08872"}},    
    {"value":"Summerbank","data":{"city":"Wyvernfield","code":"10467"}},    
];

While it works fine, I would like to format the list of sentences as: Suburb, Citybut save the value Suburbin the text field from which the autocomplete function is called.

Example:

  • If I start typing ea, this should show me:
    • Eastcliff Westwood
    • "Creastic, Westerlin"
  • If I select "Eastcliffe, Westwood", then my onSelect function should start, but the value of the text field will still remain Eastcliffe.

How do I format a list of offers in this way?

+4
source share
2 answers

You can use a function formatResultthat allows you to:

formatResult: function (suggestion, currentValue) {} a user-defined function for formatting a sentence within a sentence container, optional.

code:

$(function() {
    $('#suburb').autocomplete({
        lookup: theData,
        minChars: 1,
        formatResult: function(suggestion, currentValue){
            return suggestion.value+','+suggestion.data.city;
        }
    });
});

Demo: https://jsfiddle.net/j6r9ka6y/

+9
source

, Autocomplete.formatResult

JS ( )

Autocomplete.formatResult = function (suggestion, currentValue) {
    var pattern = '(' + utils.escapeRegExChars(currentValue) + ')';

    return suggestion.value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/&lt;(\/?strong)&gt;/g, '<$1>') + " , " + suggestion.data.city;
};
+3

Source: https://habr.com/ru/post/1608045/


All Articles