Return values with Bootstrap's Typeahead displayKey Function
Asked Answered
M

1

9

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"
    }
]
Management answered 25/7, 2015 at 10:31 Comment(0)
M
19

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!

Management answered 29/7, 2015 at 11:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.