Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead.js - Populate dataset

I am using the Twitter typeahead.js header and the following is my code that works. However i would like to know if there was a way I could populate my dataset using a function instead of an array in local. Your help is much appreciated.

    <input id="look" placeholder="search" autocomplete="off" />
        <button id="btn">Submit</button>

        <script type="text/javascript">
            $("#look").typeahead({
                name: 'accounts',
//Would like to use a function to populate my dataset here instead of this array
                local: ['timtrueman', 'JakeHarding', 'vskarich']
            });

            $("#btn").click(function () {
                $("#look").typeahead('setQuery', 't');
                $("#look").focus();
            });

        </script>
</body>
like image 291
user1288906 Avatar asked Nov 27 '25 00:11

user1288906


1 Answers

Since local provides only static data, I think remote suits your need better:

$('#look').typeahead({
    name: 'accounts',
    remote: '/your/backend/url?q=%QUERY'
});

So typeahead will send AJAX request to /your/backend/url with parameter q with value is the value you type. Your backend should be able to return a response for that lookup request.

If you want to debug the response from your backend and process that data, use this:

$('#look').typeahead({
    name: 'accounts',
    remote: {
        url: '/your/backend/url?q=%QUERY',
        filter: function(resp) {
            var dataset = [];
            console.log(resp); // debug the response here

            // do some filtering if needed with the response          

            return dataset;
        }
    }
});

Hope it helps.

like image 180
Hieu Nguyen Avatar answered Nov 28 '25 15:11

Hieu Nguyen