Handle enter in Typeahead as clicking on first suggestion

568 Views Asked by At

My Typeahead.js setup is currently working for mouse clicks on the suggestions, but not the Enter key. I'm trying to add Javascript to handle it but it's not behaving. The tt-suggestion class is generated on the fly by typeahead and I see it when I inspect the code in Chrome. What I'm wanting it to do is to trigger the link that's generated by typeahead.js rather than go to a search page that I don't have or want.

JS:

    //handle Enter key
    $("#search-box").keypress(function(e){
        if(e.which == 13) {
            $(".tt-suggestion:first-child", this).trigger('click');
        }
    });

    //bloodhound
    jQuery(document).ready(function($) {
        jQuery(document).ready(function($) {
            // Set the Options for "Bloodhound" suggestion engine
            var engine = new Bloodhound({
                remote: {
                    url: '/search/file?q=%QUERY%',
                    wildcard: '%QUERY%'
                },
                datumTokenizer: Bloodhound.tokenizers.whitespace('q'),
                queryTokenizer: Bloodhound.tokenizers.whitespace
            });

            $(".search-input").typeahead({
                hint: true,
                highlight: true,
                minLength: 1,
            }, {
                displayKey: 'name',
                source: engine.ttAdapter(),

                // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
                name: 'filesList',

                // the key from the array we want to display (name,id,email,etc...)
                templates: {
                    empty: [
                        '<div class="list-group search-results-dropdown"><div class="text-muted">Nothing found.</div></div>'
                    ],
                    header: [
                        '<div class="list-group search-results-dropdown twitter-typeahead">'
                    ],
                    footer: [ '</div>'],
                    suggestion: function (data) {
                        return '<a href="/file/' + data.id + '/" class="list-group-item" style="background:#333;">' + data.name + '</a>'
                    }
                }

            });
        })});

HTML:

                <!-- SEARCH -->
                <li class="search">
                    <a href="javascript:;">
                        <i class="fa fa-search"></i>
                    </a>
                    <div class="search-box" id="search-box">
                        <form class="typeahead" role="search">
                            <div class="input-group">
                                <input type="search" name="q" placeholder="File Search" class="form-control search-input" autocomplete="off" />
                            </div>
                        </form>
                    </div>
                </li>
                <!-- /SEARCH -->
0

There are 0 best solutions below