用户从typeahead.js中选择结果后如何保存价值?

时间:2017-08-09 07:23:29

标签: javascript jquery typeahead.js

问题我想在用户从列表中选择状态后获取状态的值。到目前为止,我有以下内容似乎无法正常工作。

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

$ state.val()似乎是一个我无法访问的预先输入的对象。我也不希望用户在jquery保存值之前单击输入框外部,只有在用户从建议列表中选择结果时才会这样做。

这是我目前的代码:

HTML:

<form>
    <div>
      <input class="state tt-input">
    </div>
    <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);
    };
  };

Typeahead object

Value is correct.

0 个答案:

没有答案