Chivorn Kouch Chivorn Kouch - 1 year ago 110
CoffeeScript Question

typeahead.bundle.js how to start searching by pressing ENTER on the dropdown suggestions?

I managed to make it do the search by clicking on the DropDown suggestions. But it does not respond when I press ENTER.

app/assets/javascripts/custom.coffee

$ ->
movies = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/movies/autocomplete?query=%QUERY',
wildcard: '%QUERY'
}
});

$('#query').typeahead(null, {
source: movies
});

$('.tt-menu').on 'click', ->
$('#search_form').submit()

$('.tt-menu').on 'keypress', (e) ->
if (e.which == 13)
$('#search_form').submit()


Any help would be really appreciated!

Answer Source

I have looked into the javascript file typeahead.bundle.js.

_onEnterKeyed: function onEnterKeyed(type, $e) {
            var $selectable;
            if ($selectable = this.menu.getActiveSelectable()) {
                this.select($selectable) && $e.preventDefault();
            }
        }

$e.preventDefault() have stop ENTER to trigger keypress event in custom.coffee. After removing it removing $e.preventDefault() I can select the suggestion from the dropdown list and make it search instantly. So the code should look like this:

_onEnterKeyed: function onEnterKeyed(type, $e) {
            var $selectable;
            if ($selectable = this.menu.getActiveSelectable()) {
                this.select($selectable);
            }
        }

Also I have to remove the code below completely:

$('.tt-menu').on 'keypress', (e) ->
    if (e.which == 13)
        $('#search_form').submit()

Now Everything works as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download