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 t
There are a few ways the input can be filled with the selected value:
Dealing with (1) and (2) first, you can handle the corresponding before events:
$('#the-typeahead').on('typeahead:beforeselect', function ($event, suggestion) {
// do whatever with the suggestion
// then either call $event.preventDefault(), or return false to cancel the event
return false;
})
Method (3) is a bit trickier. There is a beforecursorchange event, but if you cancel it, you won't move through the menu. This is probably not what you want.
The simplest way I've found to deal with this is to replace the setInputValue method on the typeahead's input object, and prevent the value being set:
// get the actual typeahead instance
let typeahead = $('#the-typeahead').data('ttTypeahead');
// capture the existing method
let old = typeahead.input.setInputValue;
typeahead.input.setInputValue = function setInputValue(value) {
// Allow clearing the input
if (value === '') {
old.call(typeahead.input, value);
}
}
Replacing this method stops the input value from being set by the library at all, so you'll need to consider if you really want to do this. In the above example, I've allowed clearing the input to still work, as this is useful for me. Using this approach, you don't need to bother with handling the beforeselect and beforeautocomplete events.
If replacing the setInputValue method is too much, you could instead replace the moveCursor function on the typeahead instance, but that means re-implementing a lot more code. You'd also need to handle the beforeselect and beforeautocomplete events in this case.
Either way, replacing internal methods isn't great, but seeing as the project is effectively abandoned, that's not so much of a problem.