bionut
bionut

Reputation: 51

Prevent typeahead.js dropdown from closing on select

How can I prevent a typeahead dropdown from closing when an item is selected? I've tried using preventDefault like this:

$('#q').bind('typeahead:selected',function(obj, datum, name) {  
            ...
            obj.preventDefault();
        });

But no success.

Edit: I've managed to "fix" this by building Typeahead with lines 217-218 commented from typeahead_views.js:

  byClick && utils.isMsie() ?
       utils.defer(this.dropdownView.close) : this.dropdownView.close();

But there has to be another way without modifying source files?

Upvotes: 5

Views: 3077

Answers (4)

Samuel Colvin
Samuel Colvin

Reputation: 13279

Had the same problem and the (very easy) solution doesn't seem to be documented anywhere

$(document).on('typeahead:beforeclose', function(event, data) {
  event.preventDefault()
})

(this just prevents the dropdown from closing at all which can be very helpful during development, use 'typeahead:beforeselect' if you want to prevent closing just on selet).

Upvotes: 2

brauliobo
brauliobo

Reputation: 6315

A simpler way:

     input.data('tt-typeahead')._selectOld = input.data('tt-typeahead')._select
     input.data('tt-typeahead')._select = function(datum) {
       if (false)
         this._selectOld(datum)
     }

Upvotes: 0

MrYellow
MrYellow

Reputation: 408

I'm working on typeahead inside tokenfield so the first part is me accessing the Typeahead.dropdown object, which in itself took some hunting.

Tried toying with isOpen or overwriting close functions, in the end closest I got was this. Breaking down the marshalling of events. You'd have to reimplement any saving of values etc, basically the first 3 lines of Typeahead.select.

I myself was blocked at being able to put a form (focus stays in input field) in the dropdown and still a bit more hunting if were to put something interactive in there. Think I'll go for a roll-your-own solution on this one but might help someone who just wants to block the closing, put the original function in a var to put it back in place when you're finished.

$('input[id="test"]').data('bs.tokenfield')
    .$input.data('ttTypeahead').dropdown.trigger = function(e) {};

Also this has potential:

$('input[id="test"]').data('bs.tokenfield')
    .$input.data('ttTypeahead').eventBus.trigger = function(e) {};

Upvotes: 0

theAlexPoon
theAlexPoon

Reputation: 342

Trigger the focus of the input on the closed callback.

    $('#typeahead-input').on('typeahead:closed', function(e, d) {
      $('#typeahead-input').focus();
    });

Upvotes: 0

Related Questions