Search code examples
javascripttypeahead.jstwitter-typeahead

how to disable typeahead:active when focusing a filled-in text field in a remote typeahead.js


I'm using typeahead.js and it's great but here's my use case: I have a text field that is already filled in with a string on the server side when the page is loaded, so I don't want the suggestions menu to be shown when the user focuses the text field.

typeahead.js seems to always show the menu when focusing the text field. This makes sense since minLength is 2 and the text field value is something like "Tony" (or whatever). But I've tried using hint: false and calling $('.typeahead').typeahead('close') inside a callback for the typeahead:active event, and neither seem to stop the menu from being shown.

Here's the init code I'm using:

$('#locationInput').typeahead({
    hint: false,
    highlight: false,
    minLength: 2
},
{
    name: 'locations',
    display: 'name',
    source: typeaheadLocations, // a simple Bloodhound instance
    templates: {
        suggestion: function(locationObj) {
            return $('<div>' + locationObj.name + '</div>');
        }
    }
});

There is a slight delay between when I focus the text field and the menu is actually shown, because the remote GET has to be run. So I'm guessing I would need to prevent that somehow, after it's focused.


Solution

  • Looks like closing the menu in the typeahead:open event does the trick, but this seems pretty hack-ish to me. :(

    $('#locationInput').typeahead({
        hint: true,
        highlight: true,
        minLength: 2
    },
    {
        name: 'locations',
        display: 'name',
        source: typeaheadLocations,
        templates: {
            suggestion: function suggestion(locationObj) {
                return $('<div>' + locationObj.name + '</div>');
            }
        }
    
    }).on('typeahead:open', function(e) {
        var $input = $(e.currentTarget);
    
        if (!$input.data('wasFocusedOnce')) {
            $input.data('wasFocusedOnce', true);
            $input.typeahead('close');
        }
    
    }).on('typeahead:close', function(e) {
        $(e.currentTarget).removeData('wasFocusedOnce');
    }).on('keydown', function(e) {
        $(e.currentTarget).data('wasFocusedOnce', true);
    });
    

    If anyone knows of a better way to do this, I'm all ears!