Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - DevBridge Autocomplete - Change suggestion format

I've got the Autocomplete jQuery plugin from DevBridge working more or less how I want it to. Please see the fiddle here: https://jsfiddle.net/shalan/bcex6oaq/. It is a simple Suburb and City lookup whereby the user starts typing in his/her suburb and the autocomplete shows relavnt suggestions. When the user makes a selection, it will automatically populate 2 readonly textboxes below with the associated City and Postal/Zip Code. The data structure looks like this:

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 great, I would like to format the suggestions list as: Suburb, City, but retain the Suburb value in the textbox from which the autocomplete function is called.

Example:

  • If I start typing ea, it should show me:
    • "Eastcliffe, Westwood"
    • "Creastwich, Westerlyn"
  • If I select "Eastcliffe, Westwood", then my onSelect function should run, but the value of the textbox should still remain as Eastcliffe.

How do I format the suggestions list in this manner?

like image 468
Shalan Avatar asked Sep 18 '15 15:09

Shalan


1 Answers

You can use formatResult function it allows you to:

formatResult: function (suggestion, currentValue) {} custom function to format suggestion entry inside suggestions 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/

like image 154
Irvin Dominin Avatar answered Nov 09 '22 21:11

Irvin Dominin