I’m trying to make a search of some items with a jquery ui autocomple in a django app. I have looked at this question, and I’m following just like autocomplete doc. I’m not interested in plugins or something else. I got this.
In views.py:
def search_view(request):
q = request.GET['term']
ret = []
listado = Model.objects.filter(descripcion__istartswith=q).order_by("descripcion")
for l in listado:
ret.append({'label':l.descripcion, 'value':l.id})
return HttpResponse(simplejson.dumps(ret), mimetype='application/json')
In my template, I have something like this
the js:
$("#auto_material").autocomplete({
source:'{% url search_view %}',
minLength: 2,
select: function( event, ui ) {
$("#auto_material").val(ui.item.label);
$("#id_material").val(ui.item.value);
}
});
the html:
<input type="text" id="auto_material" name="material" class="campo" style="width:99%;"/>
<input type="hidden" id="id_material" />
Everything in the search of items works fine, but when I’m trying to set the text input value with the ui.item.label it keeps putting the ui.item.value on the text input, not the label.
Any idea? Is the “select” event on the autocomplete object overridable? Any idea?
Thanks in advance.
From the autocomplete documentation:
And for the
selectcallback:Emphasis mine (spelling mistake theirs). In the jQuery-UI autocomplete source code, we find this:
So the widget will set the text input’s value to
item.valueafter yourselectevent handler returns. Unless of course (as noted in the documentation above) your event handler returnsfalse. Try adjusting yourselecthandler to be like this:This is documented behavior so it should be safe.