Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return values with Bootstrap's Typeahead displayKey Function

I have defined a custom template for suggestions in Bootstrap's Typeahead as mentioned below. But when I select any of the suggestions, I get only the country name in input. Since I have passed country in displayKey parameter. Is there anyway that I can select both the country and city name in input (Same as in template)?

Here is the JsFiddle: http://jsfiddle.net/geekowls/agrg3xhj/

I have also read the Examples on Typeahead website. But didn't find anything relevant. All I Know is that the displayKey parameter can take a function.

$(document).ready(function () {

                        var dataSource = new Bloodhound({
                            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country', 'city'),
                            queryTokenizer: Bloodhound.tokenizers.whitespace,
                            identify: function (obj) { return obj.country; },
                            prefetch: "../Data/1.json"

                        });

                        function dataSourceS(q, sync) {
                                dataSource.search(q, sync);          
                        }

                        $('.typeahead').typeahead( {
                            minLength: 0,
                            highlight: true
                        }, {
                            name: 'countries',
                            displayKey: 'country',
                            source: dataSourceS,
                            templates: {
                                empty: [
                                    '<div class="empty">No Matches Found</div>'
                                ].join('\n'),
                                suggestion: function (data){
                                    return '<div>' + data.country + ' – ' + data.city + '</div>'
                                }
                            }
                        }
                        );
});

Here is the Json file.

[
    {
    "country": "Holland",
    "city": "Amsterdam"
    },
    {
    "country": "Belgium",
    "city": "Brussel"
    },
    {
    "country": "Germany",
    "city": "Berlin"
    },
    {
    "country": "France",
    "city": "Paris"
    }
]
like image 674
geekowls Avatar asked Jul 25 '15 10:07

geekowls


1 Answers

The function was simple enough. Just needed to update the display parameter as:

display: function(item){ return item.country+'–'+item.city}

Also updated the code on fiddle here: http://jsfiddle.net/geekowls/agrg3xhj/1/

Cheers!

like image 193
geekowls Avatar answered Nov 03 '22 19:11

geekowls