提前输入 Bloodhound 排序 return 值。

Type-ahead Bloodhound sort return values.

我正在提前使用 Twitter 类型,但发现很难将结果与 mysql 查询分开。

我的 json 输出如下所示:{"id":"1","name":"Bravo"}

在当前状态下,预先输入的结果显示名称和 ID,我希望能够仅显示名称,但输入的实际提交值是 ID。我的剧本是流动的:

<script type="text/javascript">
// Instantiate the Bloodhound suggestion engine
var suggestions = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'includes/livesearch.php?key=%QUERY',       
        wildcard: '%QUERY',
        filter: function (name) {
            // Map the remote source JSON array to a JavaScript object array
            return $.map(name, function (name) {
                return {
                    value: name
                };
            });
        }
    }
});
// Initialize the Bloodhound suggestion engine
suggestions.initialize();

// Instantiate the Typeahead UI
$('.typeahead').typeahead({
    hint: true,
    minLength: 2
}, {
    limit: 7,
    displayKey: 'value',
    source: suggestions.ttAdapter(),
});
</script>

非常欢迎任何帮助或建议我如何实现这一目标。

谢谢!

您可以创建一个对象来存储当前检索到的值。在 Bloodhoundfilter 选项中,将对象 属性 设置为 name.name,并将值设置为 name.id.

至 return 并仅显示检索到的 JSONname 属性,使用 $.map()index 参数检查 属性对象的名称。如果 属性 是 "name" return {value:name},否则 return null.

使用 typeahead:selected 事件设置 <form><input type="hidden"> 元素的值,使用 .typeahead input 的当前值作为 属性 引用先前存储的初始 return 对象 filter 值。设置将值存储到空对象的变量引用。

 <form>
   <input class="typeahead" type="text" placeholder="search">
   <input type="hidden" name="result" value="" />
   <input type="submit">
 </form>

$(function() {
  // Instantiate the Bloodhound suggestion engine
  var curr = {};
  var suggestions = new Bloodhound({
    datumTokenizer: function(datum) {
      return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'includes/livesearch.php?key=%QUERY',       
        wildcard: '%QUERY',
        filter: function (name) {
          curr[name.name] = name.id;
            // Map the remote source JSON array to a JavaScript object array
            return $.map(name, function (name, index) {
                return index === "name" ? {
                    value: name
                } : null;
            });
        }
    }

  });
  // Initialize the Bloodhound suggestion engine
  suggestions.initialize();

  // Instantiate the Typeahead UI
  $(".typeahead").typeahead({
    hint: true,
    minLength: 2
  }, {
    limit: 7,
    displayKey: 'value',
    source: suggestions.ttAdapter(),
  })
  .on("typeahead:selected", function (e, datum) {
    $("form [name=result]").val(curr[datum.value]); // set value here
    curr = {};
  });
})

plnkrhttp://plnkr.co/edit/PJjzxemAQ9fO3P5YBfXi?p=preview