Skip to content

Instantly share code, notes, and snippets.

@stloc
Created December 8, 2022 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stloc/fed6903fc530caebdb18c303c76ae697 to your computer and use it in GitHub Desktop.
Save stloc/fed6903fc530caebdb18c303c76ae697 to your computer and use it in GitHub Desktop.
<h3>
Autocomplete des villes Françaises depuis https://geo.api.gouv.fr/communes
</h3>
<p>
Utilisation de l'élément HTML datalist https://developer.mozilla.org/fr/docs/Web/HTML/Element/datalist
</p>
<input type="text" id="lieu" name="lieu" required="required" maxlength="255" autocomplete="off" list="datalist-cities">
<datalist id="datalist-cities"></datalist>
class Autocomplete {
constructor() {
document.getElementById('lieu').addEventListener('input', (e) => {
if (typeof e.inputType !== "undefined") {
this.searchCity(e.target.value)
console.log('searchCity', e.target.value)
} else { // option selected
console.log('selected', e.target.value)
// todo what you want more
//document.getElementById('hiddenInsee').value =
//document.querySelector("#datalist-cities option[value='" + e.target.value + "']").dataset.insee;
}
});
}
searchCity(cityName) {
fetch('https://geo.api.gouv.fr/communes?nom=' + cityName + '&limit=5')
.then((resp) => resp.json())
.then((cities) => {
var datalistCities = document.getElementById('datalist-cities');
datalistCities.innerHTML = ""; // clear options
let options = "";
cities.forEach(function(city) {
var option = document.createElement('option');
option.value = city.nom;
option.innerText = city.nom;
// optionnel :
//option.dataset.insee = city.INSEECommune;
//option.dataset.workfolder = city.workfolder;
options += option.outerHTML;
});
datalistCities.innerHTML = options;
})
.catch(function(error) {
console.log(error);
});
}
}
new Autocomplete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment