Created
December 8, 2022 08:32
-
-
Save stloc/fed6903fc530caebdb18c303c76ae697 to your computer and use it in GitHub Desktop.
Autocomplete datalist. https://jsfiddle.net/stloc84/ner9k73u/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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