开发者

Jquery Autocomplete with Django

开发者 https://www.devze.com 2023-03-11 14:20 出处:网络
I\'m trying to make a search of some items with a jque开发者_如何学JAVAry ui autocomple in a django app. I have looked at this question, and I\'m following just like autocomplete doc. I\'m not interes

I'm trying to make a search of some items with a jque开发者_如何学JAVAry 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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消