Jesse Aldridge
Jesse Aldridge

Reputation: 8149

typeahead not doing anything

I type and nothing happens. No suggestions appear.

If I inspect the element I can see typeahead has modified the DOM, yet no popup appears.

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/typeahead.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        var colors = ["red", "blue", "green", "yellow", "brown", "black"];
        $('.typeahead').typeahead({source: colors});
    })
</script>
<input class='typeahead'>

Upvotes: 0

Views: 181

Answers (1)

rorofromfrance
rorofromfrance

Reputation: 1904

As per examples shown here http://twitter.github.io/typeahead.js/examples/ you need a function to handle parsing results back.

This would work:

$(function() {
    var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function(i, str) {
                if (substrRegex.test(str)) {
                    // the typeahead jQuery plugin expects suggestions to a
                    // JavaScript object, refer to typeahead docs for more info
                    matches.push({ value: str });
                }
            });
            cb(matches);
        };
    };

    var colors = ["red", "blue", "green", "yellow", "brown", "black"];
    $('.typeahead').typeahead( {}, {source: substringMatcher(colors)} );
});

Upvotes: 2

Related Questions