如何从typeahead.js结果中获取<input />值?

时间:2017-08-08 17:16:05

标签: javascript jquery typeahead.js bloodhound

这是我目前的代码:

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);
    };
  };

问题1:我想获取用户最终选择的状态的值。到目前为止,我有以下内容似乎无法正常工作。

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

$ state.val()似乎为null或空白。

问题2:代码似乎只允许第一个div上的typeahead,而不是第二个div。但它应该在相对的基础上查看输入。所以不确定为什么它不起作用。感谢。

0 个答案:

没有答案