Programmatically triggering typeahead.js result display

后端 未结 17 1836
余生分开走
余生分开走 2020-11-30 05:01

I am using Twitter\'s typeahead.js (https://github.com/twitter/typeahead.js/) on an input field which is pre filled from a query string. After loading the page, i\'d like to

17条回答
  •  自闭症患者
    2020-11-30 05:22

    Here's a simplified version of @Sam_Butler's work: http://jsfiddle.net/rimian/hrnf9

    
    
    

    Javascript:

    $('#button').click(function() {
      $("#text").focus().typeahead('val', 'London');
    });
    
    // instantiate the bloodhound suggestion engine
    var locations = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: 'https://maps.googleapis.com/maps/api/geocode/json?address=%QUERY&components=country:GB&sensor=false®ion=uk', //add key
            filter: function (locations) {
                return $.map(locations.results, function (location) {
                    return {
                        value: location.formatted_address
                    };
                });
            }
        }
    });
    
    locations.initialize();
    
    $('#text').typeahead(null, {
        name: 'value',
        displayKey: 'value',
        source: locations.ttAdapter()
    });
    

提交回复
热议问题