Twitter bootstrap typeahead custom keypress ENTER function

前端 未结 3 1628
孤城傲影
孤城傲影 2020-12-30 08:20

I\'m working with Twitter bootstrap on a Django site I\'m making. I have a page where users can enter all of their technical skills in a text input equipped with a bootstra

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 09:13

    Demo

    Instead of listening for a keypress (what if the user makes a selection with their mouse?), we can take advantage of the custom events Twitter's Typeahead emits. Namely,

    • typeahead:selected – Triggered when a suggestion from the dropdown menu is explicitly selected.

    Capturing the selection

    You can listen for it using jQuery's .on() method, and you will be provided with information about the user's selection in the second argument.

    $('input.typeahead').on('typeahead:selected', function(event, selection) {
      alert(selection.value);
    });
    

    Clearing the input field

    From there you can do as you like with the selection.value. The only "gotcha" would be trying to clear the input using .val(). Since Typeahead does quite a bit of fancy DOM rewriting, you'll need to use their 'setQuery' method as well.

    $('input.typeahead').typeahead('setQuery', '');
    

提交回复
热议问题