I am new using the typeahead.js with Django . I am also using handlebars_min.js . When I write three characters, the elements of my list that match the search are displayed. When I click, the element is put in input
. The problem is that when I choose the element and give click
outside the input
, the value
of input
disappears.
Here is my code
Views.py
def json_destino(request):
destino = request.GET.get('q', None)
if not destino:
return HttpResponse(json.dumps({}))
destinos = Clientes.objects.filter(nombre__icontains=destino)
vl = [{'name': c.nombre,'destino': c.nombre} for c in destinos]
vl = vl[:10]
ret = json.dumps(vl[:10])
return HttpResponse(ret)
File autocomplete.js
$(function()
{
var engine1 = new Bloodhound({
remote: '/destino/name/json/?standard=true&q=%QUERY',
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
});
engine1.initialize();
$('#id_destino').typeahead({minLength: 3,highlight: true}, {
name: 'destino',
displayKey: 'id',
source: engine1.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No se ha encontrado ningun elemento',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<p style="border: 1px solid red; padding: 5px;">'+
'<span class="text-primary" style="font-size:20px;">{{name}}</span><br>' +
'</p>')
}
}).bind('typeahead:selected', function(obj, datum) {
taselected(obj, datum);
}).bind('typeahead:autocompleted', function(obj, datum) {
taselected(obj, datum);
});
function taselected(obj, datum) {
$("#div_id_destino").click();
$("#id_destino").val(datum.destino);
}
});
HTML
<div id=div_id_destino>
<input type="text" name="destino" id="id_destino" />
</div>
<script src="{% static 'js/autocomplete.js' %}"></script>