How to prevent Twitter typeahead from filling in the input with the selected value?

前端 未结 5 1588
深忆病人
深忆病人 2020-12-18 08:17

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

5条回答
  •  Happy的楠姐
    2020-12-18 09:03

    There are a few ways the input can be filled with the selected value:

    1. clicking a suggestion with the mouse
    2. pressing the 'tab' key to autocomplete with the top-most suggestion
    3. using the cursor keys to move through the list of suggestions

    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.

提交回复
热议问题