【发布时间】:2016-01-26 14:34:02
【问题描述】:
我正在尝试使用 typeahead 来简化复杂查询的处理。 So the idea is to use typeahead to show a list of options and when one is choosen, set the input with the label of the choosen item and set an input hidden with the id of that item.还有一种情况需要解决,每次输入一个字母,typeahead的来源就发生变化,导致这些字段大约有40000个选项,所以使用的服务得到了前10个过滤器。
html代码:
<div id="bloodhound" class="col-sm-7">
<input class="typeahead" type="text" id="iCliente" onkeyup="actualizarArray();">
</div>
<input type="hidden" id="selectedId">
脚本代码:
function actualizarArray()
{
var clientesProcesados;
$('#bloodhound .typeahead').typeahead('destroy');
var urlTypeahead = 'http://localhost:8082/contratantes/search/findTop10ByNombreContaining?nombre=' + $('#iCliente').val();
$.ajax({
url: urlTypeahead,
type: "GET",
dataType: 'json',
success: function (data){
//alert('entro');
//TODO procesar JSON para que bloodhound lo pueda levantar
var arrayClientes = data._embedded.contratantes;
var arrayClientesProcesados = [];
for(var i in arrayClientes)
{
//var clienteStr = /*'{\"id\":\"' + arrayClientes[i].id + '\",\"nombre\":\"'*/ + arrayClientes[i].nombre /*+'\"}'*/;
arrayClientesProcesados.push(arrayClientes[i].nombre);
}
clientesProcesados = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: arrayClientesProcesados
});
$('#bloodhound .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'clientesProcesados',
source: clientesProcesados
});
$('#iCliente').focus();
}
});
}
问题是,当对象数组设置为源时,预输入不显示任何选项,所以我不知道我在做什么错。这段代码,只显示 arrayClientes[i].nombre,工作正常;并且每次触发 onkeypress 时,源更新都会完美运行。所以我错过了使用对象数组设置预输入源的部分,仅显示 arrayClientes[i].nombre,然后使 onselect 事件使用所选项目的 id 设置隐藏输入。 任何人都可以帮助我吗?
【问题讨论】:
-
尝试在
.typeahead({})之前调用clientesProcesados.initialize(),将source设置为clientesProcesados.ttAdapter()
标签: javascript jquery typeahead.js