Typeahead.js: Option for Automatic selection of the first item in the typeahead resultset

Created on 22 Feb 2013  Â·  51Comments  Â·  Source: twitter/typeahead.js

Would it be possible for there to be an option for the first item to be automatically selected in the typeahead on search so a press of the enter key will go to that specific item's url? This would save the user needing to press the downarrow key to get to that first item and then pressing the enter key. Thanks!

Most helpful comment

Here's a good workaround, that automatically selects the first so that enter works:

}).bind('typeahead:render', function(e) {
    $('#search_form').parent().find('.tt-selectable:first').addClass('tt-cursor');
});

All 51 comments

I don't know if we'll ever add anything like this as I think this behavior would be potentially confusing to the end-user. You may be able to implement this behavior after v0.9 is released, but it'd be based on custom events and not a configurable option.

Thanks for responding on this! Some of the bigger websites (eg facebook) use this, and jQuery UI autocomplete has this as an option as well. Looks like i'll have to play around with typeface v.9+.

I agree with jharding, but in some case it could be great to have the option.
ie: when the user typed his query and there is only one item left in the list. The user still have to select the line (most basic user don't really use tab)

A use case I need to support is to have a generic "Search for _< typed input >_" entry as the first item. It would make sense that this item is selected by default.

I outlined a workaround in #142. Also, see #141 for adding the generic "Search for" entry.

+1

If you're interested, I implemented this in a fork.

https://github.com/nagiek/typeahead.js

:+1: for an option

:+1:

+1

+1

@nagiek Hi, please where exactly is it implemented?

No ETA, this isn't very high priority for me. I would consider accepting a pull request for this issue though.

We added functionality to typeahead on our own.
https://github.com/UrbanCompass/typeahead.js

We use it like:

    searchBox.typeahead({
      name: 'neighborhoods',
      local: neighborhoods,
      minLength: 0,
      limit: Infinity
   })

But our version is no where near pull-request quality.

What would be a good name for this option?

autoselect: 'first'

Sjlu,

Both your auto-selecting the first option and the allowing minLength of 0 look really useful.

I would love to see a pull request for both.

It's very hacky, we'll make it a little more beautiful then submit a pull request.

Just need time to do so ;)

You may not have to submit a pull request as an autoselect option has been added to v0.10 and I also added the ability to render default suggestions, although not by using minLength: 0.

+1

Please add this to the documentation

Is this available for use yet in 0.3.2? I don't see an autoselect anywhere in the source.

+1

Sounds like the current ETA for v0.10 is early January (https://twitter.com/JakeHarding/status/405450330109775872). Thanks, @jharding!

Second that, thanks @jharding

I have found a quick-fix untill the real update is out there:

        $('.your-typeahead').on('keydown', function(event) {
            // Define tab key
            var e = jQuery.Event("keydown");
            e.keyCode = e.which = 9; // 9 == tab

            if (event.which == 13) // if pressing enter
                $('.your-typeahead').trigger(e); // trigger "tab" key - which works as "enter"
        });

I believe that when autoselect: true, that the 1st item should also have the tt-cursor class to indicate it is selected. I opened an issue to track this, but was not sure if there was a way to put it in v0.10 milestone - https://github.com/twitter/typeahead.js/issues/567

Atleast, this is the way all other typeahead/autocomplete plugins work that have an option to "autoselect" or "selectFirst".

This works for me, until a fix is submitted. Basically triggers the 'down arrow' followed by 'Enter' to select the first item in the list.

$('.typeahead').on('keydown', (event) ->
    e = jQuery.Event("keydown")
    e.keyCode = e.which = 40

    if (event.which == 13)
        event.stopPropagation()
        $('.typeahead').triggerHandler(e)
        e.keyCode = e.which = 9             
        $('.typeahead').triggerHandler(e)
)

the autoselect:boolean feature is still undocumented

\o

var $tautocomplete = $('#scrollable-dropdown-menu .typeahead');
$tautocomplete.typeahead({
  autoselect: true
},{
  name: 'countries',
  displayKey: 'name',
  source: countries.ttAdapter()
}).on('keyup', function(){

  var keyCode = e.keyCode || e.which;

  if ( keyCode !== 40 && keyCode !== 38 ) {
    $('.tt-dataset-states .tt-suggestion').first().addClass('tt-cursor');
  }

});

Would be great if this were documented!

+1 for updating documentation

what? documentation updated? i cant figure this one out..

There's no mention of autoselect in the documentation.

The documentation can be found here

Happy to contribute once I get home.

Also the autoselect feature really needs the add "tt-cursor" so the user actually knows, "autoselect" is enabled.

I was afraid it was not being maintained anymore, until I bumped into this:
https://twitter.com/falkowski/status/556138762494046208
Well, still worrying, but at least there's hope :)

@canfiax Sure, that's the next thing to do. Let's open a new issue for that feature.

Is autoselect: true working?

I'm using it but nothing happens.

@PierBover Yes, it works for me. I'm using v0.10.5. Could you share some code?

It should work fine. But remember that the CSS-class that highlights the first selection is not added, which is why you might think it does not work.

Should a typehead:selected event be dispatched?

It works fine.but i don't think this is good idea.

Please add this below a line highlighted.
//This is the function
_updateHint: function updateHint() {
var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match;
$selectable = this.menu.getTopSelectable();
data = this.menu.getSelectableData($selectable);
val = this.input.getInputValue();
if (data && !_.isBlankString(val) && !this.input.hasOverflow()) {
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(data.val);
match && this.input.setHint(val + match[1]);
*****************************

******************************
} else {
this.input.clearHint();
}

It would be great if there was an option to make 'Enter' behave same as 'Tab' (to autocomplete with first match). Something like: http://getbootstrap.com/2.3.2/javascript.html#typeahead

I just tried doing this with autoselect: true, but it doesn't work(I'm on .11.1). This issue is closed, but I still don't see the correct way its supposed to work.

Edit, ah, it looks like this feature was removed in .11.1, and so this issue should be reopened. I'll try one of the workarounds until then.

Here's a good workaround, that automatically selects the first so that enter works:

}).bind('typeahead:render', function(e) {
    $('#search_form').parent().find('.tt-selectable:first').addClass('tt-cursor');
});

+1 not working autoSelect: true

so not sure if this is still a problem for other people but it was for me... I ended up forcing the situation by using a globally scoped variable

I am using version 0.11.1

these are the additional events i added to the standard issue select and auto complete events

                .on('typeahead:render', (e,firstOption) => {
                    if (!!firstOption) {
                        enterSelection = firstOption
                    } else {
                        enterSelection = undefined;
                    }
                }).on('keypress', (e) => {
                    if (e.which == 13 && enterSelection) {
                        $('#typeahead').typeahead('val', enterSelection.value);
                        (this.onDataSelect || _.noop)({ selection: enterSelection });
                        $('#typeahead').typeahead('close');
                    }
                });

things to note. I used an id of "typeahead" and not a class, the global variable i used was enterSelection

I ended up getting the enter button to act exactly like the tab button

Thanks for the help! after seeing that the last commit in typeahed was two
years ago i think i will keep working with select2

2016-10-10 19:07 GMT-03:00 jake roth [email protected]:

so not sure if this is still a problem for other people but it was for
me... I ended up forcing the situation by using a globally scoped variable

I am using version 0.11.1

these are the additional events i added to the standard issue select and
auto complete events

            .on('typeahead:render', (e,firstOption) => {
                if (!!firstOption) {
                    enterSelection = firstOption
                } else {
                    enterSelection = undefined;
                }
            }).on('keypress', (e) => {
                if (e.which == 13 && enterSelection) {
                    $('#typeahead').typeahead('val', enterSelection.value);
                    (this.onDataSelect || _.noop)({ selection: enterSelection });
                    $('#typeahead').typeahead('close');
                }
            });

things to note. I used an id of "typeahead" and not a class, the global
variable i used was enterSelection

I ended up getting the enter button to act exactly like the tab button

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/twitter/typeahead.js/issues/32#issuecomment-252758952,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAUSinmV2Bswo9mBe22MVoEnYYGziatpks5qyrcggaJpZM4Ac5Fx
.

_May the source be with you._

I combined above mentioned solution. This selects in single "Enter" key.

             $('#supplier').typeahead({
                    highlight: true,
                    minLength: 1
                },
                {
                    name: 'supplier',
                    source: suppliers,
              }).on('keydown', function(e){
                var e = jQuery.Event("keypress");
                e.keyCode = e.which = 9; // 9 == tab
                if (event.which == 13) // if pressing enter
                    $(this).trigger(e); // trigger "tab" key - which works as "enter"

            }).bind('typeahead:render', function(e) {
                $('#supplier').parent().find('.tt-selectable:first').addClass('tt-cursor');
            });

https://codepen.io/Artistan/pen/LywrXj

This makes a dataset based on the current input query be the first option.

Was this page helpful?
0 / 5 - 0 ratings