如何在用户选择结果时保存typeahead.js结果?

时间:2017-08-21 21:13:31

标签: javascript jquery typeahead.js typeahead

问题我想在用户从列表中选择状态后获取状态的值。到目前为止,我有以下内容:但是,每次用户键入字符时结果都会保存,而不是在用户选择了值时保存:

  $('form').on("change", ".state", function(e){
    var $contextualDiv = $(e.target).closest('div');
    var $state = $contextualDiv.find('.state');
    $state.each(function(i,v){
         console.log($(v).val());
    });
    ...

看起来这也不是通过对象访问所选对象的正确方法。根据文档,我应该能够通过以下方式获取它:

var $ state = $(' .state')。typeahead(' val');

这是我目前的代码:

HTML:

<form>
    <div>
      <input class="state tt-input">
    </div>
    ...
</form>

jquery / typeahead.js实现:

<script>
    $(document).ready(function() {

    var bh = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: {
          url: '/get_states/',
          prefetch: function(settings) {
            settings.type = "GET";
            return settings;
          }, 
        },
      });

  $('.state').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'states',
      source: bh,
  });

  var substringMatcher = function(strs) {
      return function findMatches(q, cb) {
      var matches, substringRegex;

      // an array that will be populated with substring matches
      matches = [];

      // regex used to determine if a string contains the substring `q`
      substrRegex = new RegExp(q, 'i');

      // iterate through the pool of strings and for any string that
      // contains the substring `q`, add it to the `matches` array
      $.each(strs, function(i, str) {
        if (substrRegex.test(str)) {
          matches.push(str);
        }
      });

      cb(matches);
    };
  };

请更换变量&#39;航空公司&#39;与'#state;&#39;在图片中。 Typeahead object

Value is correct.

1 个答案:

答案 0 :(得分:0)

当用户选择一个选项时,typeahead库会触发一个事件。该事件的名称为.pack()。以下是documentation中提供的示例:

typeahead:select

您可以根据实施情况调整此方法。

我认为这会奏效:

$('.typeahead').bind('typeahead:select', function(ev, suggestion) {
   console.log('Selection: ' + suggestion);
});