How can I select the first given option? I'm feeding the autocomplete widget with the data from reverse geocoding results (city) basing on user's location. I have a database with cities and I need to select the first suggested option.
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();
Thanks for your help.
Screenshots:
References:
You have to select the choice programmatically too:
$('#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]);
The idea is to trigger 'selectChoice' on a first auto-complete suggestion.
Here's how to auto select the first choice if there is only one:
$(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]);
}
}
});
According to 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]);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.