Searching for Typeahead and Bloodhound docs I haven't found something helpful os what I'm doing wrong because I'm only getting suggestions when I type the first letter, but I continue typing the word and it goes to no match found. I found a way of reading JSON and filtering it on this question, but nothing else. Seems like word recognition isn't working as intended. Please someone with experience with this snippet could enlighten me on what I'm missing.
JAVASCRIPT
var globalCats = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'js/data.json',
filter: function (list) {
return $.map(list, function (item) {
return {
nombre: item.nombre,
id: item.id,
padre: item.padre
};
});
}
}
});
globalCats.initialize();
$('.typeahead').typeahead({
highlight: true
},
{
name: 'recomendaciones',
displayKey: 'nombre',
source: globalCats.ttAdapter(),
templates: {
empty: [
'<div class="card red white-text"><strong>No hay sugerencias para su búsqueda</strong></div>'
].join('\n'),
suggestion: Handlebars.compile('<div class="card"><a href="busqueda.php?catid={{id}}"><strong>{{nombre}}</strong> - Departamento {{padre}}</a></div>')
}
});
HTML
<form class="col s12 z-depth-1">
<div class="row">
<div class="col s12">
<p>Ingrese sus términos de búsqueda o de click en Solicitar Servicio para publicar su requerimiento en sus redes sociales.</p>
</div>
<div class="input-field col s12 m9">
<input id="buscador" type="text" placeholder="VEAMOS" class="typeahead">
</div>
</div>
</form>
JSON
[
{
"nombre": "Operadores de Taladradoras",
"id": 111454,
"padre": "Construcción"
},
{
"nombre": "Operadores de Maquinaria",
"id": 454654,
"padre": "Construcción"
},
{
"nombre": "Estilistas",
"id": 454678,
"padre": "Belleza"
}
]
The datumTokenizer
is wrong.
I don't understand this part very well, but I've found what seems to work in all the variations I've tried. The tokenizer needs to reference the object you are returning. So, change the tokenizer from the default to this:
Bloodhound.tokenizers.obj.whitespace('nombre'),
Also, I would recommend changing to remote
instead of prefetch
unless you are certain that the amount data returned will be very small.
Here is a link to a working example.