How to prevent Twitter typeahead from filling in t

2019-01-25 23:18发布

I'm using Twitter's typeahead plugin for autocompletion with a text input. I want to change the behavior so that instead of putting the selected option's value into the text input (when clicked), it does something else with it.

Is there any way to prevent typeahead from automatically filling in the input with the selected option's value?

4条回答
成全新的幸福
2楼-- · 2019-01-25 23:22

Struggled with this for a while, before I found how to clear the text when you select an option:

$("#typeahead-input").on('typeahead:selected', function (event, datum, name) {
   $(this).typeahead("val", "");
   // Do something with the datum...
});
查看更多
Luminary・发光体
3楼-- · 2019-01-25 23:26

Same as @Nate's answer except in version (0.11.1), the event is called typeahead:close not typeahead:closed and the only parameter is the event:

$("#input").typeahead(
    // ...
)
.on('typeahead:close', function (evt) {
    console.log(evt);
    $(obj.currentTarget).val("");
});
查看更多
手持菜刀,她持情操
4楼-- · 2019-01-25 23:31

While not necessarily the intention of typeahead, if you use it for a SEARCH PAGE this little tidbit will be very useful I feel as I was looking for this answer myself.

Unbind Selection Event From Typeahead Results List:

$('.typeahead.users').typeahead({
            rateLimitWait: 250,
            limit: 100,
            valueKey: 'title'

}).on('typeahead:opened', function (obj, datum, name) {
    $('span.tt-dropdown-menu').unbind(); //UNBINDS TYPEAHEAD SELECTION EVENT
});

WTF Did You Do? : -- When typeahead object is opened, we simply unbind the selection action altogether in order to do what we want it to instead without closing it.

Further Notes: This is sort of destructive, but if you are using for, say, a search page where the body of the result item is link to a profile with a follow button on the right to click - then the auto-filling is a super pain in the ass to fight off.

Hope this helps! Know its a bit late but maybe anyone else looking for this in the future.

查看更多
疯言疯语
5楼-- · 2019-01-25 23:45

I tried every other thing under the sun, but just stumbled across a solution a few minutes after posting my question.

In case anyone else needs help with this, adding the typeahead:closed event handler allows you to catch the entered value, as well as clear it from the input before it can be seen (maybe there's a way to prevent it from ever being entered into the input, but I haven't been able to find it).

So here's what I'm doing:

      $("#input").typeahead({
            highlight: true
        },
        {
            name: 'my-dataset',
            displayKey: 'value',
            source: bloodHound.ttAdapter()
        }
    ).on('typeahead:closed', function (obj, datum, name) {
          $(obj.currentTarget).val("");
      });
查看更多
登录 后发表回答