正确使用 Typeahead?

Proper use of Typeahead?

我有一个远程 Typeahead 示例 运行。但是,我想知道我是否将其用于预期目的。

本质上,即使它显示了适当的内容,我也需要提交显示数据的唯一标识符。

遥控器 URL 将 return 像这样:

[{"id":"123456789", "email":"me@server.com", "value":"Me Lastname"}]

所以,显示Me Lastname,但实际提交123456789?

我的直觉告诉我我需要别的东西,也许是这样的: Select2 ?

也许你可以使用 typeaheadcustom events 做这样的事情:

.typeahead({
 ......
},
{
 .......
})
.on('typeahead:selected', onSelected);

请注意 .on,它会触发像这样的自定义函数:

function onSelected($e, datum){
  //do your stuff depending on your implementation
  // you might want to fill an hidden field with the id
  // and submitting your form, or something else.
  // you can access your json in this way
  console.log(id); //="123456789
  console.log(email); //="me@server.com
  console.log(value); //="Me Lastname"

here 你可以找到一些例子

我最终使用了以下 jQuery/Bootstrap3 库:Select2