以编程方式选择django-autocomplete-light中的第一个建议

时间:2013-05-19 19:12:17

标签: javascript python django autocomplete django-autocomplete-light

如何选择第一个给定选项?我正在根据用户的位置向反自动完成小部件提供来自反向地理编码结果(城市)的数据。我有一个城市数据库,我需要选择第一个建议的选项。

autocomplete_light_registry.py

autocomplete_light.register(
    City,
    search_fields=('^name',),
    autocomplete_js_attributes={'placeholder': _('Start typing...')}
)

forms.py

class CustomerForm(forms.ModelForm):
    city = forms.ModelChoiceField(City.objects.all(), label=_('City'), widget=autocomplete_light.ChoiceWidget('CityAutocomplete'))

locations.js

$('#id_city_text').val(ymaps.geolocation.city);
var autocomplete = $('#id_city_text').yourlabsAutocomplete();
autocomplete.refresh();

感谢您的帮助。

截图:

参考文献:

3 个答案:

答案 0 :(得分:4)

您还必须以编程方式选择选项:

$('#id_city_text').val(ymaps.geolocation.city);
var autocomplete = $('#id_city_text').yourlabsAutocomplete();
autocomplete.show('<span class="div" data-value="'+ymaps.geolocation.cityId+'">'+ymaps.geolocation.city+'</span>');
$('#id_city_text').trigger('selectChoice', [autocomplete.box.find(':first-child'), autocomplete]);

这个想法是在第一个自动完成建议时触发'selectChoice'。

答案 1 :(得分:2)

以下是如果只有一个选项,如何自动选择第一个选项:

        $(document).ready(function() {
            var autocomplete = $('#id_city_text').yourlabsAutocomplete();
            autocomplete.show = function(html) {
                yourlabs.Autocomplete.prototype.show.call(this, html)
                var choices = this.box.find(this.choiceSelector);

                if (choices.length == 1) {
                    this.input.trigger('selectChoice', [choices, this]);
                }
            }
        });

答案 2 :(得分:1)

根据https://github.com/yourlabs/django-autocomplete-light/issues/139#issuecomment-18332107

<强> locations.js

$('#id_city_text').val(ymaps.geolocation.city);
var autocomplete = $('#id_city_text').yourlabsAutocomplete();
autocomplete.refresh();
autocomplete.show = function(html) {
    yourlabs.Autocomplete.prototype.show.call(this, html)
    var choices = this.box.find(this.choiceSelector);

    if (choices.length == 1) {
        this.input.trigger('selectChoice', [choices, this]);
    }
}