Jquery Autocomplete with Django

空扰寡人 提交于 2019-12-03 13:48:45

问题


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.


回答1:


From the autocomplete documentation:

The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item.

And for the select callback:

Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item.

Canceling [sic] this event prevents the value from being updated, but does not prevent the menu from closing.

Emphasis mine (spelling mistake theirs). In the jQuery-UI autocomplete source code, we find this:

if ( false !== self._trigger( "select", event, { item: item } ) ) {
    self.element.val( item.value );
}

So the widget will set the text input's value to item.value after your select event handler returns. Unless of course (as noted in the documentation above) your event handler returns false. Try adjusting your select handler to be like this:

select: function( event, ui ) {
    $("#auto_material").val(ui.item.label);
    $("#id_material").val(ui.item.value);
    return false;  // <--------------------- Add this
}

This is documented behavior so it should be safe.



来源:https://stackoverflow.com/questions/6273941/jquery-autocomplete-with-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!